
Originally Posted by
ProgramThis
The method you have is about as simple and as elegant as it gets.
Inefficiency isn't elegant.
Don't use recursion for the Fibonacci sequence. It's running time is exponential --(3/2)^N. Every CS book that has a chapter on algorithmic analysis tells you this.
Code:
public class Test {
private final static int N = 40;
public static void main(String[] args) {
long start = System.currentTimeMillis();
int a = 0, b = 1, c = 1;
for (int i = 4; i <= N; i++) { // i = 4 -> 5 -> 6 -> 7 ...
a = b; // a = 1 1 2 3
b = c; // b = 1 2 3 5
c = a + b; // c = 2 3 5 8
}
long end = System.currentTimeMillis();
System.out.println("f_" + N + " = " + c + " and iteratively took " +
(end - start) + " milliseconds.");
start = System.currentTimeMillis();
c = fib(N);
end = System.currentTimeMillis();
System.out.print("f_" + N + " = " + c + " and recursively took " +
(end - start) + " milliseconds.");
}
private static int fib(int n) {
if (n <= 3)
return 1;
return fib(n - 1) + fib (n - 2);
}
}
Output:
Code:
f_30 = 514229 and iteratively took 0 milliseconds.
f_30 = 514229 and recursively took 16 milliseconds.
f_40 = 63245986 and iteratively took 0 milliseconds.
f_40 = 63245986 and recursively took 672 milliseconds.
f_50 = -811192543 and iteratively took 0 milliseconds. (longs obv. don't work well with big N)
f_50 = -811192543 and recursively took 77359 milliseconds. (1 minute 17.359 seconds...)