Question: Here is a simple recursive function to compute the Fibonacci sequence: long fibr (int n) { // Recursive Fibonacci generator // fibr (46) is largest
Here is a simple recursive function to compute the Fibonacci sequence:
long fibr (int n) { // Recursive Fibonacci generator
// fibr (46) is largest value that fits in a long
Assert ( (n > 0) && (n
This algorithm turns out to be very slow, calling Fibr a total of Fib(m) times. Contrast this with the following iterative algorithm: long fibi (int n) Iterative Fibonacci generator ert (46) is largest value that fits in a long (in 0) (n 47), Input out of range") long past prev, curr; store temporary values past prev curr 1; initialize for (int i 3 n; it Compute next value past. prev past holds fibi (i-2) prev curr prev holds fibi (i-1) curr Past previ curr now holds fibi (i) return curr Function Fibi executes the for loop m 2 times (a) Which version is easier to understand? Why? (b) Explain why Fibr is so much slower than Fibi if ( (n == 1) || (n == 2) return 1; // Base cases
return fibr(n-1) + fibr(n-2); // Recursion
}
Data Structures and Algorithm Analysis in C++ by Clifford Shaffer
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
