Friday, June 7, 2013

Project Euler- Problem Number 2 Solution

Project Euler 2: Even Fibonacci numbers
Project Euler- Problem Number 2 Project Euler-Problem Number 2 Solution Project Euler-Problem Number 2 Solution in C  
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.


My first suggestion to solve this problem, read more carefully the problem and think that how should we have to do to solve it. well. At first we have to know what is Fibonacci number or Fibonacci series? What is Fibonacci formula? If we had already known any Fibonacci C program then it would be easy to us. well, Fibonacci sequence is defined as F1 = F2 = 1 .
By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
F_n = F_{n-1} + F_{n-2},\!\,
with seed values
F_0 = 0,\; F_1     = 1.

Well Now we know what is Fibonacci Number. Look at our problem. We have to generate all Fibonacci number under 4000000 and sum of all number. We use 4 variables.  A loop which is help us us generate fibonacci number under 4 millions times. Another two variables are one=1 & two=2; 
Now, C program do just a simple job that is, in three (variable name) variable it add the vaule of one & two and total variable added the value of two of it's own memory for every time. Then C program replace the value of one and two variable. One variable contains the values of two variable and two variable contains the values of three variable. Below is the C program source code of this problem:

#include<stdio.h>
#include<conio.h>
int main()
{
    long total=0,one=1,two=2,three=0;
    while(two<=4000000)
    {
        three=one+two;
        if(two%2==0)
        total+=two;
        one=two;
        two=three;
    }
    printf("%ld",total);
    return 0;
}
After completing the loop function the C program will excite it's final result. To solve this problem I use some modulo operator such as while, % ,||,if etc.While loop help us to loop the C program from 1 to 4000000 times.

No comments:

Post a Comment