Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle Database 19c DBA By Examples Installation And Administration

Authors: Ravinder Gupta

1st Edition

B09FC7TQJ6, 979-8469226970

More Books

Students also viewed these Databases questions

Question

What is the EPEAT tool? How is it used?

Answered: 1 week ago

Question

Explain the market segmentation.

Answered: 1 week ago

Question

Mention the bases on which consumer market can be segmented.

Answered: 1 week ago