This tutorial demonstrates PHP scripts that use loops and recursion to calculate the factorial of a given number.
PHP Program to Factorial Using Loop
Program:
<?php
/* Define a variable and assign a value to it to find the factorial.*/
$n = 5;
/*Define the variable where you want to store the factorial number value.*/
$f = 1;
/*Iterate the loop to find the factorial.*/
for ($i=1; $i <= $n; $i++) {
$f = $f * $i;
}
/*Display the output.*/
echo "Factorial of $n is $f";
?>
Program Output:
Factorial of 5 is 120
PHP Program to Factorial Using Recursion
Program:
<?php
/*Recursive function*/
function factorial($n)
{
if($n <= 1) {
return 1;
}
else{
return $n * factorial($n - 1);
}
}
/* Define a variable and assign a value to it to find the factorial.*/
$n = 5;
echo "Factorial of $n is " .factorial($n); /*Call the Function */
?>
Program Output:
Factorial of 5 is 120
Definition of the Factorial Function?
The factorial function is a mathematics formula represented by the exclamation mark "!". The formula finds the factorial of any number. It is defined as the product of a number containing all consecutive least value numbers up to that number. Thus it is the result of multiplying the descending series of numbers. The factorial of zero is one, and the factorial is not defined for negative numbers.
Formula:
n! = n * (n-1) * (n-2) * … * 3 * 2 * 1
or
n! = 1 * 2 * 3 * ... * n
Examples of factorial formulas
Example:
0! = 1 1! = 1 2! = 1 * 2 = 2 3! = 1 * 2 * 3 = 6 4! = 4 * 3 * 2 * 1 = 24 5! = 5 * 4 * 3 * 2 * 1 = 5 * 24 = 120 7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040