There is an issue with the recursive definition of the fibonacci sequence when it comes to efficiency. It is defined as follows:
private fib(int n) {
if(n < 2) return n;
else return fib(n - 1) + fib(n-2);
}
Suppose we call fib(5). This makes 1 call to fib(4) , two calls to fib(3), three calls to fib(2), five calls to fib(1) and three calls to fib(0).
In his book
Programming Abstractions in Java by Eric Roberts
Roberts mentions that we can resolve this efficiency issue by realizing that the fibonacci sequence is just a special case of the additiveSequence(int n, int t0, int t1) method. Basically, the Fibonacci sequence is just an additive sequence that strictly begins with 0 and 1. There are an infinite number of sequences that match the recurrence relation expressed by Fibonacci.
The author resolves the efficiency issue as follows:
private int fib(int n) {
return additiveSequence(n, 0, 1);
}
So my questions is, by making the fib sequence a wrapper for the more general additiveSequence method, are we really improving efficiency ? Wouldn't the implementation of additiveSequence have the same exact "problem" in terms of efficiency that fib had, given that it does follow the same exact reccurence relation ?
additiveSequenceis implemented. If it is implemented not efficiently, you will have efficiency problem. - Salvador DaliadditiveSequenceand that you are using that as the return statement of thefibmethod. This is why I am so confused. - Mutating AlgorithmadditiveSequenceis not a universally well known method so I would not expect people to know it. And the complexity of the algorithm and even its validity depends on this method. - Salvador Dali