Home > Article > Backend Development > How to use loop to implement factorial of n in php
php uses loops to implement the factorial of n: 1. Create a new php sample file; 2. Add the delimiter of php; 3. Declare the file type and encoding for PHP to interact with the browser; 4. Define a Function compute(), and add the parameter $num; 5. Use the for statement to calculate the factorial of the parameter $num; 6. Use the return statement to return the calculated result.
The operating environment of this tutorial: Windows 10 system, PHP version 8.1, Dell G3 computer.
How to use loop to realize the factorial of n in php?
PHP uses the loop method to find N factorial:
Create a new 318.php, as shown in the figure:
Add the delimiter of php (), as shown in the figure:
Declare the file type for PHP to interact with the browser and coding, as shown in the figure:
Define a function compute(), and add the parameter $num, the code is as shown in the figure:
Define the variable $result inside the compute() function and assign it a value of 1, as shown in the figure:
Use the for statement to calculate the parameter $num The factorial of , as shown in the figure:
Use the return statement to return the calculated result, as shown in the figure:
Call the compute() function to calculate the factorial of 9, as shown in the figure:
Run the web page and output the factorial result of 9, as shown in the figure :
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to use loop to implement factorial of n in php. For more information, please follow other related articles on the PHP Chinese website!