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.

Project Euler Problem 1

Hi Friends,

I started solving Project Euler problems recently and found them to be really interesting. So I though of discussing my approach and solutions with the world. I will code my answers in C. So here we start.

Problem 1: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

The problem is pretty easy and straight forward. Just check all the numbers from 3 to 999 if they are divisible by 3 or 5 and add them if they are.
Here is my code:
1:  #include <stdio.h>  
2:  int main(void)  
3:  {  
4:       int sum=0,i;  
5:       for(i=3;i<1000;i++){  
6:            if(i%3==0 || i%5==0)  
7:                 sum+=i;  
8:       }  
9:       printf("%d",sum);  
10:       return 0;       
11:  }  
Do comment if you have any alternate solution.