Recursion
Recursion
Recursion
f1 f1 f2 … fn
How long shall we continue this process? We know that 0! = 1, but there is no
sense for calculating factorial for negative numbers. The equality 0! = 1 or f(0) = 1 is
called simple case or terminating case or base case. When we need to find f(0), we do
not continue the reduction like f(0) = f(-1) * 0 because it has no sense, but simply
substitute the value of f(0) by 1. So
f(2) = f(1) * 2 = f(0) * 1 * 2 = 1 * 1 * 2 = 2
The recursive case defines the problem in terms of a smaller problem of the same
type
the recursive case includes a recursive function call
there can be more than one recursive case
f(1) * 2
1*1*2*3 = 6
f(0) * 1
1
E-OLYMP 1658. Factorial For the given number n find the factorial n!
► The problem can be solved with for loop, but we’ll consider the recursive
solution. To solve the problem, simply call a function fact(n). The value n ≤ 20, use
long long type.
long long fact(int n)
{
if (n == 0) return 1;
return fact(n-1) * n;
}
E-OLYMP 1603. The sum of digits Find the sum of digits of an integer.
► Input number n can be negative. In this case we must take the absolute value of
it (sum of digits for -n and n is the same).
Let sum(n) be the function that returns the sum of digits of n.
If n < 10, the sum of digits equals to the number itself: sum(n) = n;
Otherwise we add the last digit of n to sum(n / 10);
We have the following recurrence relation:
sum (n / 10 ) n%10, n 10
sum(n) =
n, n 10
sum(123) = sum(12) +3 = sum(1) +2 +3 = 1 +2 +3 = 6
fi 0 1 1 2 3 5 8 13 21 34 55 ...