简体   繁体   中英

how to get the factorial of a number in javascript in a recursive way?

I want to know how to find the factorial of number 4 in a recursive way. Although, I know the simple technique suppose.

let factorial = 1; for(let i=1; i<=4; i++){ factorial = factorial * i;} console.log(factorial)

If you want to learn and use same approach as the code.

You can do it this way

function factorial(n){
  return n === 1 ? n : factorial(n-1) * n;
}

So basically just do n * n-1 * n-2 * n-3... 1
For example 4, then the algorithm would run as follows: 5 * 4 * 3 * 2 * 1
When it reaches 1, the recursion should stop, because that's how factorial works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM