Solution to Problem 2. Written in Python.
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, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
num_sum = 0
ctr = 0
temp = 0
found = False
def fib(x):
if (x == 0):
return 0
elif (x == 1):
return 1
return (fib(x - 1) + fib(x - 2))
while (found == False):
temp = fib(ctr)
if (temp <= 4000000):
if (temp % 2 == 0):
num_sum += temp
ctr += 1
else:
found = True
print num_sum