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
functionFibonacciEvenSum(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 =0if n ==1return even_sumelseif n ==2 even_sum = current_termreturn even_sumelsewhile (current_term < n) next_term = current_term + previous_termif current_term%2==0 even_sum = even_sum + current_termend previous_term = current_term current_term = next_termendendreturn even_sumend
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