Home >Web Front-end >JS Tutorial >How to use for to find the factorial of n in JavaScript
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.
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++) { }
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;
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); }
Call f() function
f(2); f(3); f(4);
Output:
【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!