Project Euler 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.

Official link: https://projecteuler.net/problem=2

Thought Process

Clearly all we need to do is generate the fibonacci numbers less than 4 million and sum all those that are even.

There are 2 tricks:

(1) n % 2 == 0 will return true if n is divisible by 2, which is essential an odd or even checker

(2) The simplest code for computing fibonnaci numbers goes as follows:

f1 = 1 #Initialize f1

f2 = 1 #Initialize f2

while True:

fn = f2 + f1 #Standard fibonacci equation

(Add condition for when you want it to stop)

f1 = f2 #Now we re-assign f1 to be our old f2

f2 = fn #Similarly we re assign f2 to be our new fn

becuase we are still in the while loop our new fn = f2 + f1 will take the updated values of f1 and f2


Interactive Code

Enter a number (yourinput)

Code will output the answer from 1 to yourinput