Thursday, January 1, 2015

Project Euler problem 2 Solution in C and python

Q: 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 C:

#include <stdio.h>

int main(){
long long int a=1, b=2, sum=1, esum=2//we add 2 already bcoz we know 2 is a even term of fabanacii series;

while (sum<4000000){
printf("%d \t",sum);
sum=a+b;//sum holds the next number in the series
a=b;
b=sum;
if (sum%2==0){
esum+=b;//adding all the even terms of the series
}


}

printf("\n \nsum of even terms is %d", esum);
getchar();

}


Solution in python(3):

a=1
b=2
no=1
evensum=2
while (no<4000000):
    no=a+b
    a=b
    b=no
    if no%2==0:
        evensum=evensum+no

print(evensum)