Wednesday 14 October 2015

Project Euler #2: Even Fibonacci numbers

Hi folks, today I will show you how to solve 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,
By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms.
Solution

int i = Convert.ToInt32(Console.ReadLine());
List<decimal> list = new List<decimal>();
for (int j = 0; j < i; j++)
{
   list.Add(Convert.ToInt64(Console.ReadLine()));
}
foreach (decimal k in list)
{
   long b = 1;
   long c = 2, d;
   long sum = 0;
   while (c < k)
   {
      sum += c;
      d = b + (c << 0x01);
      c = d + b + c;
      b = d;
   }
   Console.WriteLine(sum);
}

No comments:

Post a Comment