Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java puzzle (Sum of even Fibonacci numbers)

DZone's Guide to

Java puzzle (Sum of even Fibonacci numbers)

· Java Zone ·
Free Resource

Secure your Java app or API service quickly and easily with Okta's user authentication and authorization libraries. Developer accounts are free forever. Try Okta Instead.

Write a function which calculates the sum of even Fibonacci numbers.

public static void main(String... args) {
    for(int i=1;i<22;i++)
        System.out.print(sumEvenFibonacci(i) + " ");
}

public static long sumEvenFibonacci(int n) {
    // add code here.
    return sum;
}
prints
0 0 2 2 2 10 10 10 44 44 44 188 188 188 798 798 798 3382 3382 3382 14328 
For bonus points, optimise the sumEvenFibonacci method so it contains only one condition and doesn't test for even or odd.

 

From http://vanillajava.blogspot.com/2011/11/java-puzzle.html

Secure your Java app or API service quickly and easily with Okta's user authentication and authorization libraries. Developer accounts are free forever. Try Okta Instead.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}