Finding sum of even terms in Fibonacci series

Problem :

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.

Solution :
Even terms in this series are separated by two odd numbers.(Sum of two odd numbers is even)
therefore, we get the series : 0,2,8,34,144,610…..
The terms of this series are generated as :
2 * 4 + 0 = 8
8 * 4 + 2 = 34
34 * 4 + 8 = 144
144 * 4 + 34 = 610 and so on…


public class EvenFibonacci {

	long evenFibo()
	{
		long sum = 0;
		long a = 2, b = 8, c = 0;
		
		sum = sum + a + b;
		while(true)
		{
			c = b * 4 + a;
			if(c>4000000)
				break;
			sum = sum + c;
			a = b;
			b = c;
			System.out.println(c+"   ");
		}
		return sum;
	}
	public static void main(String a[])
	{
		EvenFibonacci e = new EvenFibonacci();
		System.out.println("Sum of even terms of fibo upto 4million : " + e.evenFibo());
	}
}

Leave a comment