Problem 2 - Even Fibonacci numbers
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.
it is very fast even for numbers up to 1e200
def fibsum(maximum):
fib1 = 0
fib2 = 1
sum = 0
while fib2 < maximum:
aux = fib2
fib2 += fib1
fib1 = aux
if fib2 & 1 == 0:
sum += fib2
return sum
print fibsum(int(4e6))
No comments:
Post a Comment