Friday, March 13, 2015

(C Language) (ENG) Even Fibonacci Numbers - Project Euler Problem 2

PROBLEM



Write a program calculating summation of even Fibonacci numbers starting from "1, 2, 3, 5, 8, 13..." below 4.000.000.

This c problem is taken by me from: (https://projecteuler.net/problem=2)

SAMPLE RUN:

In addition to problem, i printed result on the screen.





SOLUTION

You can copy codes below to your compiler to execute.


#include <stdio.h>

int main(void) //main function.
{
int sum = 0; //this variable will hold summation of even Fibonacci numbers.
int a, b, c; //due to I can find summation with only 3 elements, I will use 3 elements.

a = 1; //in this question, our series starts with 1...
b = 2; //...and continuous with 2.
c = 0; //this line causes c to get into loop.

while (c < 4000000) //this loop will find the summation of even numbers.
{
c = a + b; //it will find the next element's value.

if (c % 2 == 0) //this comparison will determine if c is even or not.
sum = sum + c; //it will calculate summation of c.
a = b; //we can keep next value(which is b after a) in a with that line.
b = c; //we can keep next value(which is c after b) in a with that line.
}

sum = sum + 2; // in loop above, we find the summation except b that we initialized which is also even.

printf("Summation of even Fibonacci numbers below 4.000.000 is %d", sum); //it will print the summation on the screen.

return 0;
}

No comments:

Post a Comment