Project Euler Problem 2 Solution in Python

Even Fibonacci numbers

How to solve Even Fibonacci Numbers – Project Euler Problem 2 . We will discuss all the problems in Project Euler and try to solve them using Python. I have solved Project Euler Problem 1 Multiples of 3 and 5 in Python as well.

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.

So we have to solve this problem using Python.

I am assuming you have already installed Python 2.7.x. If not, you can download it from here.

First of all open Python IDLE.

If we analyze the problem statement given here, we can see that we are asked to calculate the sum of those even numbers who complies to the following conditions.

Say we call our number to be summed as x

  • x is even
  • x is in fibonacci series
  • x is less than 4 million

We have to add these “x” numbers.

Lets start!

We need to save the sum of such x numbers into some variable.

sumOfEvenFibonacci  = 0

Now let’s make a list to store all the fibonacci series till 4 million. If you are not sure how we came up with list of Fibonacci Series you can read my this tutorial here How to make Fibonacci Series in Python.

nums = Fibonacci()
We have to iterate the list to find out which are even number then we will add them into our sumOfEvenFibonacci variable.

Solution to Even Fibonacci numbers

for i in nums:
  if i % 2 == 0:
    countOfEvenFibonacci = countOfEvenFibonacci + i

Display the sum. It show that 4613732 is the number of such elements.

See if we got the solution to Even Fibonacci Numbers right.

Even Fibonacci numbers

Yaay! We got this right. Thanks for reading. Happy coding! 

Project euler problem 3 Largest Prime Factor solved here.

Imad

I am a Software Engineer with ample experience in making games, websites, mobile apps and augmented reality solutions.

Pin It on Pinterest