Monday, May 12, 2014

Project Euler - Problem 2 in C#

Even Fibonacci numbers

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 four million, find the sum of the even-valued terms.

We have two options to solve this problem, declarative or imperative approach. Declarative approach has two steps

  • Step 1: Generate the list of all the numbers in fibonacci series less then equal to 4 million

public static IEnumerable<int> GenerateList(int upperBound)
{
 if (upperBound < 2)
 {
  throw new Exception("Invalid upper bound");
 }

 IList<int> list = new List<int>();

 var prev1 = 1;
 list.Add(prev1);
 var prev2 = 2;
 list.Add(prev2);
 var sum = 0;

 while (sum < upperBound)
 {
  sum = prev1 + prev2;
  list.Add(sum);
                prev1 = prev2;
                prev2 = sum;
 }

 return list;
}

  • Step 2: Sum all the even numbers in the list

// OPTION 1
var sum = GenerateList(4000000)
  .Where(x => x % 2 == 0)
  .Sum();

// By creating list first and reducing list to +ve numbers and finding their sum
Console.WriteLine(sum);

    In the imperative approach, sum the even number while generating the fibonacci series in the loop itself.


    // OPTION 2
    var prev1 = 1;
    var prev2 = 2;
    
    // prev2 value is 2 which is a even number, so sum starts from 2
    var sumByLooping = prev2;
    
    while(prev2 <= 4000000
    {
     var sumOf2Nos = prev1 + prev2;
    
     prev1 = prev2;
     prev2 = sumOf2Nos;
    
     if (sumOf2Nos % 2 == 0
     {
      sumByLooping += sumOf2Nos;
     }
    }
    
    // By looping thru numbers and adding only +ve numbers
    Console.WriteLine(sumByLooping);
    


    Link to Problem #1
    Link to Problem #3

    Have fun solving problems ....

    No comments:

    Post a Comment