Implementation steps: 1. Define a variable and assign a value of 1 to store the factorial result. The syntax is "$cj=1;"; 2. Use the for statement to loop through the numbers in the range of "1~n" and find Factorial of n, syntax "for ($i = 1; $i
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the for loop to achieve Factorial algorithm.
Implementation steps:
Step 1: Define a variable and assign a value of 1 to store the factorial result
$cj=1;
Step 2: Use the for statement to loop through the numbers in the "1~n" range
If you want to find the factorial of n, you need to traverse the numbers1~n
, so for The initial condition of the loop can be set toi = 1
, and the restriction condition can bei <= n
ori < n 1
.
for ($i = 1; $i <= $n; $i++) { //循环体代码 }
Step 3: In the loop body, multiply the $i value of each loop and assign it to $cj
$cj *= $i; //或 $cj = $cj * $i;
Wait until the loop ends After that, the value of variable $cj is the factorial of n, which can be output.
Complete implementation code
function f($n){ $cj=1; for ($i = 1; $i <= $n; $i++) { $cj *= $i; } echo " $n 的阶乘值为: $cj
"; }
Call the f() function to find the factorial of 2, 3, and 4
f(2); f(3); f(4);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement factorial algorithm in php. For more information, please follow other related articles on the PHP Chinese website!