Friday 10 April 2009

PROJECT EULER #2

Link to Project Euler problem 2

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.

One of those "swapping the numbers around" jobs. I do like the conditional operator (?:) too but it sometime obfuscates the code a bit.


using System;

namespace ProjectEuler
{
class Program
{
static void Main(string[] args)
{
//Problem 2
bool stop = false;
int f1 = 1;
int f2 = 2;
int f3 = 0;
int sum = 2;
while (!stop)
{
f3 = f1 + f2;
sum += f3 % 2 == 0 ? f3 : 0;
stop = f3 > 4000000 ? true : false;
f1 = f2;
f2 = f3;
}
Console.WriteLine("{0}", sum);
}
}
}

No comments: