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
|
||||
```
|
31
1-js/06-advanced-functions/01-recursion/02-factorial/task.md
Normal file
31
1-js/06-advanced-functions/01-recursion/02-factorial/task.md
Normal file
|
@ -0,0 +1,31 @@
|
|||
importance: 4
|
||||
|
||||
---
|
||||
|
||||
# Calculate factorial
|
||||
|
||||
The [factorial](https://en.wikipedia.org/wiki/Factorial) of a natural number is a number multiplied by `"number minus one"`, then by `"number minus two"`, and so on till `1`. The factorial of `n` is denoted as `n!`
|
||||
|
||||
We can write a definition of factorial like this:
|
||||
|
||||
```js
|
||||
n! = n * (n - 1) * (n - 2) * ...*1
|
||||
```
|
||||
|
||||
Values of factorials for different `n`:
|
||||
|
||||
```js
|
||||
1! = 1
|
||||
2! = 2 * 1 = 2
|
||||
3! = 3 * 2 * 1 = 6
|
||||
4! = 4 * 3 * 2 * 1 = 24
|
||||
5! = 5 * 4 * 3 * 2 * 1 = 120
|
||||
```
|
||||
|
||||
The task is to write a function `factorial(n)` that calculates `n!` using recursive calls.
|
||||
|
||||
```js
|
||||
alert( factorial(5) ); // 120
|
||||
```
|
||||
|
||||
P.S. Hint: `n!` can be written as `n * (n-1)!` For instance: `3! = 3*2! = 3*2*1! = 6`
|
Loading…
Add table
Add a link
Reference in a new issue