Over a million developers have joined DZone.

Java puzzle (Sum of even Fibonacci numbers)

DZone's Guide to

Java puzzle (Sum of even Fibonacci numbers)

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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;
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

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}