Home > Web Front-end > JS Tutorial > How to find the factorial from 1 to 20 in javascript

How to find the factorial from 1 to 20 in javascript

青灯夜游
Release: 2023-01-07 11:46:33
Original
5996 people have browsed it

In JavaScript, you can find the factorial from 1 to 20 by nesting 2 levels of for loops. The specific syntax is "for(var i=1;i

How to find the factorial from 1 to 20 in javascript

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

In JavaScript, we can nest 2 levels of for loops to find the factorial from 1 to 20.

The implementation idea of ​​N factorial:

  • Because to find the factorial of n is to find 1 multiplied by 2 multiplied by 3...keep multiplying to the product of n. Therefore, the initial condition of the for loop can be set to i = 1, and the restriction condition can be i

  • Then the loop body is the multiplication operation. Multiply the i value of each loop to get a product

  • Finally output the product

The implementation code for finding 20 factorials is given below:

var sum = 1;
for (var i = 1; i <= 20; i++) {
    sum *= i;
}
console.log( "20的阶乘为: " + sum);
Copy after login

The output result is:

How to find the factorial from 1 to 20 in javascript

If you want to ask for the factorial from 1 to 20, you need to make some modifications based on the above code, and add a for loop outside to control what factorial is being searched for

for(var i=1;i<=20;i++){
	var sum = 1;
	for (var j = 1; j <= i; j++) {
		sum *= j;
	}
	console.log( i+"的阶乘为: " + sum);
}
Copy after login

The output result is:

How to find the factorial from 1 to 20 in javascript

[Recommended learning: javascript advanced tutorial

The above is the detailed content of How to find the factorial from 1 to 20 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