Factorial
Now that we understand both iteration and recursion, let's look at how both of them work.
As we know factorial of a number is defined as:
n! = n(n-1)(n-2)...1
or in other words:
n! = n(n-1)!
Let's now implement both an iterative and recursive solution for factorial in C++.
Both solutions look intuitive and easy to understand. The iterative version has a control variable i
, which controls the loop so that the loop runs n
times. For the iterative solution, we know in advance exactly how many times the loop would run.
The recursive version uses the second definition: n! = n * (n - 1)!
, which is naturally a recursive
definition. It defines the factorial of n
in terms of the factorial of a smaller version (n - 1)
. We don't need to specify in advance, how many times the loop will run.
xxxxxxxxxx
// Iterative
function factorialIterative(n) {
let result = 1;
for (let i = n; i >= 1; i--) {
result = result * i;
}
return result;
}
​
// Recursive
function factorialRecursive(n) {
let result = 0;
​
if (n == 1)
// base case: n==1
result = 1;
// recursive case
else result = n * factorialRecursive(n - 1);
​
return result;
}
​
factorialIterative(4);
factorialRecursive(4);