D
D
Dmitry2019-02-14 14:39:30
PHP
Dmitry, 2019-02-14 14:39:30

How to read code with recursion?

I am learning php. Got code:

spoiler
function factor($n)
{
if ($n <= 0) return 1;
else return $n * factor($n — 1);
}
echo factor(20);

It's not clear to me why subtract 1:
$n * factor($n — 1);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey S., 2019-02-14
@seganim

Because the factorial is the product of all positive numbers up to the current one. Starting from the desired number, we multiply it by the previous one at each iteration until we get 0, which will return 1.
For 5, these are the steps:
5 4 3 2 1 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question