Fibonacci in Java

Basic recursive fibonacci in Java. Very inefficient. Set N >= 50 to see why.

How can we make this code more efficient when a) still using recursion, b) re-coding iteratively?

public class Fibonacci {
    public static long fibonacci(int n) {
        if (n <= 1) 
        	return n;
        	return fibonacci(n-1) + fibonacci(n-2);
    public static void main(String[] args) {
        int n = 10;
        for (int i = 1; i <= n; i++) {
            System.out.println("N:" + i + ": " + fibonacci(i));

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at

Up ↑

%d bloggers like this: