Slow Fibonacci Recursion
in
Programming Questions
•
10 months ago
I wrote this recursive function to calculate the nth term of the Fibonacci sequence:
long f(long n){
if(n <= 0){ return n * -1; }
return f(n - 1) + f(n - 2);
}
The problem is it runs extremely slow, with inputs over about 40 taking minutes and the time to complete increasing directly with the size of the answer. I believe it is because the function can only add by 0 or 1 each time it reaches its base case (n == 0 or n == -1).
Does someone have a suggestion on how to dramatically speed up the function while remaining concise?
1