Question: Objective Some functions are most naturally expressed in a recursive form. For example, the Fibonacci sequence is often defined recursively as: F(n) - Fn -1)
Objective Some functions are most naturally expressed in a recursive form. For example, the Fibonacci sequence is often defined recursively as: F(n) - Fn -1) Fn -2). For such a definition to be useful, it must lead to values which are non-recursively defined; the base cases for the Fibonacci sequence are F(O)-0 and F(1)- 1. Unfortunately, calling a function recursively can be expensive in terms of execution time and memory Background Another famous recursive function is the Euclidean algorithm, used to compute the greatest common divisor of two integers. The following is the function definition: r ify=0 gcd(z, y) = ged(v, remainder(x. u) if z 2 and 0 The following is the pseudocode for the ged function: function gcdRecursive is: input: integer x, integer y such that xy and y >- 0 1. if y is o, return x 2. otherwise, return ged y, (remainder of x/ly) 1 end ged Below is a version of the same algorithm using explicit iteration. By maintaining its state entirely in the variables x and y and using a looping construct, the program avoids making recursive calls and growing the call stack. function gedIterative is: input: integer x, integer y such that x >= y and y >_ 0 1. create new variable called remainder 2. begin loop a. if y is zero, exit loop b. set remainder to the remainder of x//y c. set x to y d. set y to remainder e. repeat loop 3. return x end ged Problem statement: In this lab, we want to: (1) use recursion to implement a version of the ged function, (2) use iteration to implement a version of the ged function, and (3) analyze the results from
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
