tenten321
-
Python,
pasted
on Dec 10:
|
#Project Euler Problem 2:
#
#Find the sum of all the even-valued terms in the sequence
# which do not exceed four million.
f_n_minus_2 = 1
f_n_minus_1 = 2
f_n = 0
even_fibonaccis = [f_n_minus_1]
for n in range(3,4000000):
f_n = f_n_minus_1 + f_n_minus_2 #For this iteration: n = n-1 + n-2
#Stop when f_n greater than 4million
if f_n > 4000000:
break
if f_n % 2 == 0:
even_fibonaccis.append(f_n)
f_n_minus_2 = f_n_minus_1 #For the next iteration: n-2 = n-1
f_n_minus_1 = f_n #For the next iteration: n-1 = n
#Finally, sum the list.
print "n =", n
print even_fibonaccis
print "Sum of even Fibonacchi's:", sum(even_fibonaccis)
|
Output:
|
n = 33
[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
Sum of even Fibonacchi's: 4613732
|
|