Home > Web Front-end > Front-end Q&A > How to find the factorial of 5 in javascript

How to find the factorial of 5 in javascript

藏色散人
Release: 2023-01-07 11:41:04
Original
4845 people have browsed it

Javascript method to find the factorial of 5: 1. Use a while loop to find the factorial of 5, code such as "while(num){result *= num;num--;}"; 2. Use a function to find the factorial recursively The factorial of 5, the code is like "function factorial(){...}".

How to find the factorial of 5 in javascript

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

How to find the factorial of 5 in javascript?

JS implements the factorial operation of 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
Copy after login

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

Running result:

[Recommendation: JavaScript advanced tutorial

The above is the detailed content of How to find the factorial of 5 in 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