How to generate only even fibonacci numbers instead of iterating over all Fibonacci numbers.
Fibonacci numbers
The even number Fibonacci sequence is, 0, 2, 8, 34, 144, 610, 2584….
If we take a closer look at Fibonacci sequence, we can notice that every third number in sequence is even and the sequence of even numbers follow following recursive formula.
Recurrence for Even Fibonacci sequence is:
EFn = 4EFn-1 + EFn-2
with seed values
EF0 = 0 and EF1 = 2.EFn represents n’th term in Even Fibonacci sequence.
proof :-
Fn = Fn-1 + Fn-2 [Expanding both terms]
= Fn-2 + Fn-3 + Fn-3 + Fn-4
= Fn-2 + 2Fn-3 + Fn-4 [Expending first term]
= Fn-3 + Fn-4 + 2Fn-3 + Fn-4
= 3Fn-3 + 2Fn-4 [Expending one Fn-4]
= 3Fn-3 + Fn-4 + Fn-5 + Fn-6 [Combing Fn-4 and Fn-5]
= 4Fn-3 + Fn-6Since every third Fibonacci Number is even, So if Fn is
even then Fn-3 is even and Fn-6 is also even. Let Fn be
xth even element and mark it as EFx.
If Fn is EFx, then Fn-3 is previous even number i.e. EFx-1
and Fn-6 is previous of EFx-1 i.e. EFx-2
So
Fn = 4Fn-3 + Fn-6
which means,
EFx = 4EFx-1 + EFx-2
Now since you know the recursive relation , now you can code the rest.
here i have provided the code with proper comments :-
In case of any doubt feel free to ask 