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, \dots$$
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
def fib_even_sum(y):
a = 1
b = 2
even_sum = 0
while b <= y:
if b % 2 == 0:
even_sum += b
a, b = b, a + b
print(even_sum)
y = 4000000
fib_even_sum(y)
4613732
Here is a solution to Euler Problem number 2, which is to get the sum of all the numbers of the Fibonacci sequence up to 4,000,000. This is done by first starting with the first two terms of the sequence, checking if b
is even (this eventually checks all of the numbers aside from a
and does not need to check a
, because a
is 1, which is odd). If b
is even, then it gets added to even_sum
. a
and b
are then reproduced to get the next number in the sequence, and this process repeats until the number in the b
variable reaches 4,000,000.