Wednesday, June 9, 2010

Project Euler Problem 2 in C

    So ProjectEuler once again. This time it's problem two. Problem is:
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, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

    So it involves going up to 4 million... that was a bit confusing. Originally, I had an array of ints (int fib[4000000]) but that didn't last too long as every time I ran it it would crash. To get around that, I lowered the figure down until it was still reaching all the fibonacci series below 4,000,000 but wasn't going to crash the program. So here's the code:

#include <stdio.h>

int main()
{
long int fib[400000]={400000, 0};
long int total=2; //fib[1] is not added as the loop starts at fib[2]
int i=0;

fib[0]=1;
fib[1]=2;

for(int i=2; i<=400000; i++)
{
fib[i]=fib[i-2]+fib[i-1];
if(fib[i]>4000000)
goto end;
if(fib[i]%2==0)
total+=fib[i];
}

end:
printf("%d\n", total);
return 1;
}

Execution time: 0.171 s

    Yeah, yeah. I know. Don't use goto but it was just so handy! again, all comments welcome.
       NotMyFault


1 comment:

  1. You should use a "%ld" instead of "%d" ont he final output:

    printf("%ld", total);

    You initialized total as a long integer.

    ReplyDelete