Saturday, January 25, 2014

Project Euler Problem 2

Problem 2: 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.

Solution:
In general the n’th number in the Fibonacci sequence is defined as Fn = Fn-1 + Fn-2.
So here is the brute force approach:
This approach is very easy. Just compute the next Fibonacci number and check if its even or not. If it is even, then add it to the sum otherwise move on.

 #include <stdio.h>  
 int main(void)  
 {  
      int sum=2,first=1, second=2, third=3;  
      while(third<4000000)  
      {  
           if(third%2 == 0)  
         {  
                sum+=third;  
           }  
         first = second;  
           second = third;  
           third = first + second;  
      }  
      printf("%d",sum);  
      return 0;       
 }  

Now lets try to get an efficient solution. If we look at the Fibonacci sequence:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
we can notice the pattern that every third number is even starting from third term. So nth term can be expressed as:
F(n) = F(n-1) + F(n-2)
We want to express this term in terms of 3 and 6. So,
F(n) = F(n-2)+F(n-3)+F(n-2)=2 F(n-2) + F(n-3)
F(n) = 2(F(n-3)+F(n-4))+F(n-3))=3 F(n-3) + 2 F(n-4)
F(n) = 3 F(n-3) + F(n-4) + F(n-5) + F(n-6)
F(n) = 4 F(n-3) + F(n-6)

I leave the code as an exercise to the reader. Thanks for reading the post. If you liked it then do comment.

No comments:

Post a Comment