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

How to use for to find the factorial of n in JavaScript

青灯夜游
Release: 2022-09-30 15:22:28
Original
10848 people have browsed it

How to use for to find n factorial: 1. Use the "for (var i=1;i<=n;i){}" statement to control the loop traversal range to "1~n"; 2. Loop In the body, use "cj*=i" to multiply the numbers from 1 to n, and assign the product to the variable cj; 3. After the loop ends, the value of the variable cj is the factorial of n and can be output.

How to use for to find the factorial of n in JavaScript

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

JavaScript uses for to find the factorial of n

If you want to find the factorial of n, you need to traverse the numbers from 1 to n, so the initial condition of the for loop can be set to i = 1, the restriction can be i <= n or i < n 1.

for (var i = 1; i <= n; i++) {
}
Copy after login

Then in the loop body "{}", multiply the i values ​​of each loop. This requires an intermediate quantity cj to store the product. The initial value of the variable cj must be 1, so as not to affect the result. There are two ways to write it (just choose one):

cj *= i;
//或
cj = cj * i;
Copy after login

After the loop ends, the value of variable cj will be the factorial of 10, and then output it.

The complete implementation code is given below:

function f(n){
	var cj=1;
	for(var i=1;i<=n;i++){
		cj*=i;
	}
	console.log(cj);
}
Copy after login

Call f() function

f(2);
f(3);
f(4);
Copy after login

Output:

1 (1).png

【Related recommendations: javascript learning tutorial

The above is the detailed content of How to use for to find the factorial of n 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!