Trusted answers to developer questions

Educative Answers Team

The **factorial of a non-negative** number,*n*, is computed as the product of all integers between 1 and n (both inclusive).

$factorial(n)=n * (n-1) * ... * 1$

It can also be thought of as:

$factorial(n)=n * factorial(n-1)$

Note:The factorial of 0 is 1.

There are two ways to compute the factorial of a number in JavaScript.

- Iterative
- Recursive

Both of these approaches will be explored below.

Keeping in mind the first definition of a factorial, the variable `i`

is initially set equal to `n`

and is gradually decremented to 1. In each step, the result of the multiplication is stored in the variable `answer`

.

The table below shows how the values of `i`

and `answer`

vary with each iteration.

`i` |
`answer` |
---|---|

4 | 4 |

3 | 4 * 3 = 12 |

2 | 12 * 2 = 24 |

1 | 24 * 2 = 1 |

**Pro**: Takes less memory than the recursive implementation.

**Con**: The code is lengthier than that of the recursive implementation.

function factorial(n){ let answer = 1; if (n == 0 || n == 1){ return answer; }else{ for(var i = n; i >= 1; i--){ answer = answer * i; } return answer; } } let n = 4; answer = factorial(n) console.log("The factorial of " + n + " is " + answer);

As stated above, the factorial of `n`

can be found by finding the factorial of a number one less than `n`

, and then multiplying this answer with `n`

. So the factorial of n-1 can be thought of as a subproblem that needs to be computed first.

The table below shows the value returned by each function call.

function call | `return` value |
---|---|

factorial(1) | 1 (base case) |

factorial(2) | 2 * 1 = 2 |

factorial(3) | 3 * 2 = 6 |

factorial(4) | 4 * 6 = 24 |

**Pro:** Shorter and cleaner code.

**Con:** Greater memory requirements as all the function calls remain on the stack until the base case is reached.

function factorial(n){ //base case if(n == 0 || n == 1){ return 1; //recursive case }else{ return n * factorial(n-1); } } let n = 4; answer = factorial(n) console.log("The factorial of " + n + " is " + answer);

RELATED TAGS

javascript

recursion

iteration

Copyright ©2022 Educative, Inc. All rights reserved

RELATED COURSES

View all Courses

Keep Exploring

Related Courses