Recursion: Alexander S. Kulikov
Recursion: Alexander S. Kulikov
Alexander S. Kulikov
Steklov Mathematical Institute at St. Petersburg, Russian Academy of Sciences
and
University of California, San Diego
Outline
Recursion
Coin Problem
Hanoi Towers
Line to Louvre
numberOfPeopleBefore(A):
if there is nobody before A:
return 0
B ← person right before A
return numberOfPeopleBefore(B) + 1
Factorial Function
Definition
For a positive integer n, the factorial of n is
the product of integers from 1 to n.
Factorial Function
Definition
For a positive integer n, the factorial of n is
the product of integers from 1 to n.
5! = 1 × 2 × 3 × 4 × 5 = 120 = 4! × 5
Factorial Function
Definition
For a positive integer n, the factorial of n is
the product of integers from 1 to n.
5! = 1 × 2 × 3 × 4 × 5 = 120 = 4! × 5
Recursive definition
{
1 if n = 1
n! =
n × (n − 1)! if n > 1
Iterative Program
def f a c t o r i a l ( n ) :
assert ( n > 0)
result = 1
for i i n range ( 1 , n + 1 ) :
r e s u l t *= i
return r e s u l t
Recursive Program
def f a c t o r i a l ( n ) :
assert ( n > 0)
i f n == 1 :
return 1
else :
return n * f a c t o r i a l ( n − 1 )
Termination
• No base case:
def f a c t o r i a l ( n ) :
return n * f a c t o r i a l ( n − 1 )
More Examples of Infinite Recursion
• No base case:
def f a c t o r i a l ( n ) :
return n * f a c t o r i a l ( n − 1 )
Recursion
Coin Problem
Hanoi Towers
Coin Problem
Problem
Prove that any monetary amount starting
from 8 can be paid using coins of
denominations 3 and 5.
Coin Problem
Problem
Prove that any monetary amount starting
from 8 can be paid using coins of
denominations 3 and 5.
• Looks plausibly: 8 = 3 + 5, 9 = 3 + 3 + 3,
10 = 5 + 5, 11 = 3 + 3 + 5
Coin Problem
Problem
Prove that any monetary amount starting
from 8 can be paid using coins of
denominations 3 and 5.
• Looks plausibly: 8 = 3 + 5, 9 = 3 + 3 + 3,
10 = 5 + 5, 11 = 3 + 3 + 5
• But how can we be sure that it is always
possible?
Speculating
c o i n s = change ( amount − 3 )
c o i n s . append ( 3 )
return c o i n s
Outline
Recursion
Coin Problem
Hanoi Towers
Hanoi Towers
Puzzle
There are three sticks with n discs sorted by size on
one of the sticks. The goal is to move all n discs to
another stick subject to two constraints: move one disc
at a time and don’t place a larger disc on a smaller one.
https://commons.wikimedia.org/w/index.php?curid=228623
Is It Even Possible?