Monday, March 26, 2012

Finding the sum of even valued terms in a fibonacci sequence whose values 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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int sum=0,f=1, prev1=1, prev2=0;

while( f<4000000)
{
f = prev1 + prev2;
Console.Write(f + ", ");
prev2 = prev1;
prev1 = f;

if (f % 2 == 0)
{
sum = sum + f;
}
}
Console.WriteLine("Sum of all even numbers in a fibonacci sequence where value is less than 4 million is " + sum);
}
}
}

No comments: