Introduction to Recursion - Compass(
n
−
1)!
So if we already know how to compute (n−1)!, then we can compute n! by multiplying it by n.
This naturally leads to a recursive solution.
Sum of Numbers from 1 to N
Now consider the problem of finding the sum of all numbers from 1 to N.
We can define it recursively:
- sum(0)=0
- sum(n)=n+sum(n−1)
So to compute the sum up to n, we first compute the sum up to n−1, then add n.
Fibonacci Numbers
The Fibonacci sequence is defined as follows:
- F0=0
- F1=1
- Fn=Fn−1+Fn−2 for n>1
So each value depends on the two previous ones. This definition can be translated directly into recursion.
Exponentiation
Suppose we want to compute an, where a is an integer and n is a non-negative integer.
A direct recursive definition is:
- a0=1
- an=a⋅an−1
So the recursive implementation is:
This works in O(n) time.
Fast Exponentiation
We can improve the previous method.
an=an/2⋅an/2 So instead of reducing the exponent by 1 each time, we can sometimes reduce it by half. This gives a much faster recursive solution.
The time complexity of this version is O(logn), because at many steps we divide the exponent by 2 instead of subtracting 1.
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int sum(int n) {
if (n == 0) {
return 0;
} else {
return n + sum(n - 1);
}
}
int F(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return F(n - 1) + F(n - 2);
}
}
int Pow(int a, int n) {
if (n == 0) {
return 1;
} else {
return a * Pow(a, n - 1);
}
}
int Pow(int a, int n) {
if (n == 0) {
return 1;
} else if (n % 2 == 0) {
int A = Pow(a, n / 2);
return A * A;
} else {
return a * Pow(a, n - 1);
}
}