Problem 2

Problem

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, \dots\)

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

Julia

function p2()
    a, b = 1, 2
    sum = 2
    while true
        current_fibo_term = a + b
        current_fibo_term > 4_000_000 && break
        iseven(current_fibo_term) && (sum += current_fibo_term)
        a, b = b, current_fibo_term
    end
    return sum
end;
p2()
4613732
using BenchmarkTools;
@benchmark p2()
BenchmarkTools.Trial: 10000 samples with 998 evaluations.
 Range (minmax):  15.992 ns36.813 ns   GC (min … max): 0.00% … 0.00%
 Time  (median):     16.012 ns               GC (median):    0.00%
 Time  (mean ± σ):   17.000 ns ±  2.094 ns   GC (mean ± σ):  0.00% ± 0.00%
     ▃ ▂    ▅                                              ▅ ▁
  ▄▁▃█▃██▁▄██▄▅▇▆▄█▃▄▄▅▃▄▅▃▁▄▃▃▃▃▄▃▄▄▃▁▃▁▁▄▃▄▁▃▃▁▃▃▁█▁█▄█▃█ █
  16 ns        Histogram: log(frequency) by time      21.9 ns <
 Memory estimate: 0 bytes, allocs estimate: 0.