Home > Web Front-end > JS Tutorial > body text

How to implement the factorial of n using javascript

藏色散人
Release: 2021-11-19 11:26:22
Original
6570 people have browsed it

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;
}
Copy after login

Option 2: Using function recursion

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template