Problem 2. Even Fibonacci numbers

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.

public class euler2 {
    public static void main(String[] args) {
        int i = 1;
        int N = 4000000;
        long sum = 0;
        long f = 0;
        while (f < N) {
            f = fibo(i);
            if (f % 2 == 0)
            	sum += f;
            i++;
        }
        System.out.println(sum);
    }
    public static long fibo(int i) {
        if (i < 2) return i;
        else return fibo(i-1) + fibo(i-2);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>