Question
Here is a simple recursive function to compute the Fibonacci sequence: /** Recursively generate and return the nth Fibonacci number */ static long fibr(int n)
Here is a simple recursive function to compute the Fibonacci sequence:
/** Recursively generate and return the nth Fibonacci number */ static long fibr(int n) { // fibr(91) is the largest value that fits in a long assert (n > 0) && (n <= 91) : "n out of range"; if ((n == 1) || (n == 2)) return 1; // Base case return fibr(n-1) + fibr(n-2); // Recursive call }
This algorithm turns out to be very slow, calling Fibr a total of Fib(n) times. Contrast this with the following iterative algorithm:
/** Iteratively generate and return the nth Fibonacci number */ static long fibi(int n) { // fibr(91) is the largest value that fits in a long assert (n > 0) && (n <= 91) : "n out of range"; long curr, prev, past; if ((n == 1) || (n == 2)) return 1; curr = prev = 1; // curr holds current Fib value for (int i=3; i<=n; i++) { // Compute next value past = prev; // past holds fibi(i-2) prev = curr; // prev holds fibi(i-1) curr = past + prev; // curr now holds fibi(i) } return curr; } Function Fibi executes the for loop n 2 times.
(a) Which version is easier to understand? Why?
(b) Explain why Fibr is so much slower than Fibi.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started