up
This commit is contained in:
parent
83b93e5992
commit
9ad9063d00
742 changed files with 884 additions and 779 deletions
21
1-js/06-more-functions/01-recursion/02-factorial/solution.md
Normal file
21
1-js/06-more-functions/01-recursion/02-factorial/solution.md
Normal file
|
@ -0,0 +1,21 @@
|
|||
By definition, a factorial is `n!` can be written as `n * (n-1)!`.
|
||||
|
||||
In other words, the result of `factorial(n)` can be calculated as `n` multiplied by the result of `factorial(n-1)`. And the call for `n-1` can recursively descend lower, and lower, till `1`.
|
||||
|
||||
```js run
|
||||
function factorial(n) {
|
||||
return (n != 1) ? n * factorial(n - 1) : 1;
|
||||
}
|
||||
|
||||
alert( factorial(5) ); // 120
|
||||
```
|
||||
|
||||
The basis of recursion is the value `1`. We can also make `0` the basis here, doesn't matter much, but gives one more recursive step:
|
||||
|
||||
```js run
|
||||
function factorial(n) {
|
||||
return n ? n * factorial(n - 1) : 1;
|
||||
}
|
||||
|
||||
alert( factorial(5) ); // 120
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue