Thursday, October 22, 2009

How to find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million?

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.

Note: Solve yourself before going directly to the solution

Solution:
Language: C#
int term1 = 1, term2 = 2;
int sum = 0;

while (term2 <= 4000000)
{
if ((term2 % 2) == 0)
      {
       sum += term2;
      }            
      // Switch values
      term1 = term1 + term2;
      term2 = term1 - term2;
      term1 = term1 - term2;
      // calculate next value by adding previous two terms
      term2 = term1 + term2;
}

2 comments:

Shahid Riaz Bhatti

Nice article, but It feels that its some kinda class assignments.

M Ahmad Sheikh

@Shahid Riaz Bhatti: Yup it seems like but these are some puzzle to sharpen your mind :)

Post a Comment

Thank you for your Comment!

  © Blogger template 'Minimalist F' by Ourblogtemplates.com 2008

Back to TOP