Possible Duplicate:
Python program to find fibonacci series. More Pythonic way.
Hey, i was trying to write a script which sums all the even terms in "Fibonacci Sequence" under 4 millions.
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
i = 4
for i in range(1,4000000):
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()
it should takes less than a minute, but it took all night and it wasn't solved !
Edit: Sorry guys, i misunderstood the problem. I though it means that i have to sum all the even terms UP TO 4 million ! But the solution was to sum all the even terms UNTIL 4 million.
Working code (finished in less than one second):
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
while a < 4000000:
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()