up
This commit is contained in:
parent
4ae129054e
commit
ab9ab64bd5
476 changed files with 3370 additions and 532 deletions
|
@ -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