LECTURE 23: Recursion (Chapter 10)
Definition:
A function that calls itself is said to be recursive (also, if function f1
calls function f2 that calls f1, it is called recursive).
Often,
recursion is an alternative to looping
Recursion
is computationally less efficient, but it allows writing natural-looking
programs
Example: Factorial
Definition:
n! = n*(n-1)*…*2*1 (4! = 4*3*2*1)
0! = 1
Factorial can also be defined (recursively) as:
n! = n*(n-1)! if n > 0, n! = 1 if n=0
The recursive formula can be implemented in C as:
int factorial(int n)
{
int ans;
if (n==0)
ans = 1;
else
ans = n * factorial(n-1);
return(ans);
}
Let us compare this solution to the non-recursive one:
int factorial(int n)
{
int ans;
int i;
ans = n;
for (i=n-1;
i >= 1; i++)
ans = ans
* i;
return (ans);
}
Analysis
of function factorial – “Tracing a Recursive Function”:
Read
10.2, p. 507-511
Example:
Greatest Common Divisor – gcd(m,n)
Definition: gcd is the
largest integer that divides both m and n (we will assume m > n)
gcd(6,4) = 2, gcd(12,6) = 6, gcd(7,6) = 1;
gcd can be found recursively as:
gcd(m,n) = n if m%n
= 0, gcd(m,n) = gcd(n, m%n) otherwise
To implement this solution is C:
int gcd(int m, int n)
{
int ans;
if(m%n == 0)
ans = n;
else
ans = gcd(n,
m%n);
return(ans);
}
Most
common form of recursion:
if “simple case”
solve it
else
redefine the problem using recursion