002 Overview PDF
002 Overview PDF
Find the sum of all the even-valued terms in the Fibonacci sequence
which do not exceed four million.
limit=4000000
sum=0
a=1
b=1
while b<limit
if b mod 2=0 then sum=sum+b
h=a+b
a=b
b=h
output sum
Now let us see if we can get rid of the testing for even values.
Here is the beginning of the Fibonacci sequence with even numbers in red:
1 1 2 3 5 8 13 21 34 55 89 144 ...
a b c a b c a b c a b c
limit=4000000
sum=0
a=1
b=1
c=a+b
while c<limit
sum=sum+c
a=b+c
b=c+a
c=a+b
output sum
The proof is on the following page. Perhaps you want to try that yourself first.
Copyright Project Euler, further distribution without the consent of the author(s) prohibited
Author: hk
F(n) = F(n-1) + F(n-2)
= F(n-2)+F(n-3)+F(n-2)=2 F(n-2) + F(n-3)
= 2(F(n-3)+F(n-4))+F(n-3))=3 F(n-3) + 2 F(n-4)
= 3 F(n-3) + F(n-4) + F(n-5) + F(n-6)
= 4 F(n-3) + F(n-6)
In the forum several other schemes can be found to avoid the testing for the Fibonacci
numbers to be even. If you did not find your method in this overview you might have a look
there.
Copyright Project Euler, further distribution without the consent of the author(s) prohibited
Author: hk