Home >Web Front-end >JS Tutorial >How to implement the factorial of n using javascript

How to implement the factorial of n using javascript

藏色散人
藏色散人Original
2021-11-19 11:26:226619browse

Use JavaScript to implement the factorial of n: 1. Use while loop, code such as "while(num){result *= num;num--;}"; 2. Use function recursion, code such as " if(num <= 0){return 1;}else{...}".

How to implement the factorial of n using javascript

The operating environment of this article: windows7 system, javascript1.8.5 version, Dell G3 computer.

How to use javascript to implement the factorial of n?

Two methods to implement n factorial in javascript

Option 1: Using while loop

function factorial(num){
var result = 1;
while(num){
result *= num;
num--;
}
return result;
}

Option 2: Using function recursion

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

Recommended Study: "javascript basic tutorial"

The above is the detailed content of How to implement the factorial of n using 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