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
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);
The output result is:
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); }
The output result is:
[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!