Even Fibonacci Numbers

Author

Angel Alcala Ruiz

Published

November 20, 2023

Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

\[ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... \]

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution

Let’s solve this using Julia

Code
function FibonacciEvenSum(n)

#' @@name FibonacciEvenSum
#'
#' @@description 
#' 
#' This function sums all of the even terms in the Fibonacci sequence such that the terms in the sequence are less than n
#' 
#' @@arg n: A positive integer n
#'
#' @@return The sum of all even terms in the Fibonacci that are less than n
#'
#' @@example
#'
#' n = 10
#' FibonacciEvenSum(n)

    previous_term = 1
    current_term = 2
    even_sum = 0
    
    if n == 1
        return even_sum
    elseif n == 2
        even_sum = current_term
        return even_sum
    else
        while (current_term < n)
            next_term = current_term + previous_term
            if  current_term%2 == 0
                even_sum = even_sum + current_term
            end    
            previous_term = current_term
            current_term = next_term
        end
    end
    return even_sum
end
FibonacciEvenSum (generic function with 1 method)

The even terms in the Fibonacci sequence whose values are under 10 are 2 and 8. Therefore the sum of the even terms under 10 should be 10

Code
FibonacciEvenSum(10)
10

The even terms in the Fibonacci sequence whose values are under 34 are also 2 and 8. Therefore sum of the even terms under 34 should also be 10

Code
FibonacciEvenSum(34)
10

The even terms in the Fibonacci sequence whose values are under 145 are 2, 8, 34 and 144. Therefore the sum of the even terms under 145 should be the following

Code
FibonacciEvenSum(145)
188

Now let’s find the sum of the even terms whose values are under 4,000,000

Code
FibonacciEvenSum(4000000)
4613732