Home >Backend Development >PHP Problem >How to implement factorial algorithm in php

How to implement factorial algorithm in php

青灯夜游
青灯夜游Original
2022-08-11 19:05:244908browse

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

How to implement factorial algorithm in php

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 numbers 1~n, so for The initial condition of the loop can be set to i = 1, and the restriction condition can be i or <code>i .

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 <br>";
}

Call the f() function to find the factorial of 2, 3, and 4

f(2);
f(3);
f(4);

How to implement factorial algorithm in php

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!

Statement:
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