Project Euler Problem 2 Solution in Python
Project Euler Problem 2 Solution in Python

Project Euler Problem 2 Python

How to solve “Project Euler Problem 2 Python” . We will discuss all the problems in Project Euler and try to solve them using Python. I have solved Project Euler Problem 1 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.

Lets 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.

Let’s 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.

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

 

Now lets display the sum. It show that 4613732 is the number of such elements.

Lets see if we got it right.

Project Euler Problem 2 Solution
Project Euler Problem 2 Solution

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