Week 3: Recursion (Book: Section 7.15)
Week 3: Recursion (Book: Section 7.15)
Week 3:
2
Remember from Math-lessons:
mathematical induction?
We have a functional proposition,
say P(n), where n ϵ {7, 8, 9, 10, 11, 12, 13, . . .}.
Suppose we can prove that: "starting point"
• P(7) is true, and
"wheel"
• ( A k : k>7 : P(k-1) P(k) )
4
An example
The factorial of a non-negative integer n,
written as n! (pronounced "n factorial"),
is defined as the number of ways to arrange n different objects in a row.
5
The example about n factorial, continued
A recursive definition for n!:
• n! := 1 for n=0
• n! := n * (n-1)! for n>0
Solution:
public int fac(int n)
// for n>=0 the method returns n!
{
??????
}
6
The example about n factorial, continued
public int fac(int n)
// for n>=0 the method returns n!
{
return 1;
}
This implementation is correct for n=0.
7
The example about n factorial, continued
The former ideas combined:
or recursively:
return 0; returns 0
10
About a recursive method
12
Hanoi, a difficult problem (if you don't like recursion)
3 piles (towers), numbered 1, 2, 3.
In how many moves can you solve the problem? And how should you
do it?
13
Hanoi, a difficult problem (if you don't like recursion)
14