Recursion: L. Mais Saad Safoq Computer Science Department Kerbala University
Recursion: L. Mais Saad Safoq Computer Science Department Kerbala University
power (5,4)
5 * power (5,3) 125
power (5,3)
5 * power (5,2) 25
power(5,2)
5
5 * power (5,1)
1
5 * power(5,0)
Recursively Defined Functions
The Factorial of n
How can we recursively define the factorial function f(n)
= n! ?
factorial(n) = n * [(n-1) * (n-2) * … * 1]
f(0) = 1
f(n) = n f(n-1)
f(0) = 1
f(1) = 1*f(0) = 1*1 = 1
f(2) = 2*f(1) = 2*1 = 2
f(3) = 3*f(2) = 3*2 = 6
f(4) = 4*f(3) = 4*6 = 24
A Recursive Method
A recurrence relation
A mathematical formula that generates the terms in a sequence
from previous terms
Example
factorial(n) = n * [(n-1) * (n-2) * … * 1]
= n * factorial(n-1)
A recursive definition of factorial(n)
base case factorial(n) = 1 if n = 0
fact (4)
6
4 * fact (3) 6
fact (3)
2
3 * fact (2) 2
fact (2)
1
2 * fact (1) 1
fact (1)
The Factorial of n
int factorial(int number) {
int temp;