Project Euler Problem #2 - Even Fibonacci Numbers (in Java)

  1. public class Problem_2_Even_Fibonacci_Numbers {

  2.     /*
  3.         Each new term in the Fibonacci sequence is generated by adding the previous two terms.
  4.        
  5.         By starting with 1 and 2, the first 10 terms will be:
  6.         1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

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

  9.     public static void main (String[] args) {
  10.         fibonacci(1, 2);
  11.     }

  12.     static int sum = 0, fibonacciSequence = 0;

  13.     public static void fibonacci (int i, int j) {

  14.         fibonacciSequence = j;
  15.         if (fibonacciSequence <= 4000000) { // 4 million
  16.             if (j % 2 == 0) {
  17.                 sum += j;
  18.             }
  19.             fibonacci(j, i + j);
  20.         } else {
  21.             System.out.println(sum);
  22.         }
  23.     }
  24. }
DOWNLOAD

              Created: February 10, 2014
Completed in full by: Michael Yaworski