Project Euler #2
Just finished problem 2 of Project Euler. Another simple one, sadly I was set back a good 30 minutes because of an evil semi-colon hiding in the mist of my syntax. Anyways, here's my solution in C++:
int Problem2()
{
int Answer = 0, FTerm = 0, i1 = 0, i2 = 0;
while( FTerm < 4000000 )
{
FTerm = i1 + i2;
i1 = i2; i2 = FTerm;
if( !(FTerm % 2) ) Answer += FTerm;
}
return Answer;
}
I'll try and explain that more than I did the last problem. I create 4 int variables: Answer, our return value. FTerm, the current number in our Fibonacci sequence. i1 and i2, the two previous numbers from our Fibonacci sequence.
What we do is setup a while loop that keeps pushing through our sequence until FTerm exceeds 4,000,000. Inside this loop we redefine FTerm with the sum of our two previous values. Then we use the modulo ( %) operator to find out if the current FTerm value is even by checking if there is any remainder when dividing the FTerm value by 2, if there is any remainder it is not an even number, if there isn't then it's even. If the FTerm value is even we finally add it to the Answer.