Home >Web Front-end >JS Tutorial >How to find factorial in javascript

How to find factorial in javascript

藏色散人
藏色散人Original
2021-04-01 15:13:0810266browse

How to find the factorial in javascript: 1. Use a while loop to find the factorial of a specified number; 2. Use a function to recursively find the factorial of a specified number. The code is like "function factorial(num){var result=1... }".

How to find factorial in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JS implementation example of factorial operation for finding 5.

Option 1: Using while loop


function factorial(num){
  var result = 1;
  while(num){
    result *= num;
    num--;
  }
  return result;
}
console.log(factorial(5))//120

Running result:

Option 2: Using function recursion


function factorial(num){
  if(num <= 0){
    return 1;
  }else{
    return num*arguments.callee(num-1);
  }
}
console.log(factorial(5))//120

Running result:

[Recommended Study: js basic tutorial

The above is the detailed content of How to find factorial in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn