






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Receive: n , an integer Precondition: n >= 0 (0! = 1 and 1! = 1) Return: n!
Given a set of N possible numbers to choose from Guess a number from the set
A set of N-1 numbers remains from which to guess This is a smaller version of the same problem
base case problem whose solution is trivial
Example: The factorial function has two base cases : if n = 0 : n! = 1 if n = 1 : n! = 1
induction step : a means of solving the one or
Example: In the factorial problem, we solve the
problem:
induction step.
“big” problem using a “smaller” version of the
function return Positive is
begin
if N > 1 then return N * Factorial(N-1); else return 1; end if;
end Factorial;
Factorial (N : Natural)
-- factorial
N (^4) return?
Factorial(4)
N 3 return 6
= 4 * 6
function Factorial (N : Natural) return Positive is begin – factorial if N > 1 then return N * Factorial(N-1); else return 1; end if; end Factorial;
N 4 return 24
Factorial(4)
function Factorial (N : Natural) return Positive is begin – factorial if N > 1 then return N * Factorial(N-1); else return 1; end if; end Factorial;
Factorial(3) terminates, returning 6 to Factorial(4):
For example the exponentiation problem: Given two values x and n , compute xn. Example: 3^3 = 27
usually win, because the overhead of a function call is far more time-consuming than the time to execute a loop.
recursive solution is more efficient than a corresponding loop-based solution.
For example the exponentiation problem: Given two values x and n , compute xn. Example: 3^3 = 27
Legend has it that there were three diamond needles
Stacked upon the leftmost needle were 64 golden disks, each a different size, stacked in concentric order:
If we time the for-loop version and the recursive version, the for-loop version will
However, there are problems where the
set into the floor of the temple of Brahma in Hanoi.
single move.
the five disks on top of it out of the way.
then need to move the five disks back on top of it to complete the solution.
problem, as a function of n be moved. n 1 1 2 3 3 7 4 5 ... i 2 i - 64 2 64 -1 (a big number)
-- move the top -- from needle
Let’s see how many moves it takes to solve this , the number of disks to
Number of disk-moves required
15 31