Factorial Program

The factorial of a number n is defined by the product of all the digits from 1 to n (including 1 and n).

For example


14597 = 1 + 4 + 5 + 9 + 7  
14597 = 26 
    

The simplest way to find the factorial of a number is by using a loop.
There are two ways to find factorial in PHP:

Logic:


Factorial in PHP

Factorial of 4 using for loop is shown below.


                    
<?php
$num = 4;  
$factorial = 1;  
for ($x=$num; $x>=1; $x--)   
{  
  $factorial = $factorial * $x;  
}  
echo "Factorial of $num is $factorial";  
?>  
    

Output


Factorial using Form in PHP

Below program shows a form through which you can calculate factorial of any number

Example:


                    

<html>  
<head>  
<title>Factorial Program using loop in PHP</title>  
</head>  
<body>  
<form method="post">  
    Enter the Number:<br>  
    <input type="number" name="number" id="number">  
    <input type="submit" name="submit" value="Submit" />  
</form>  
<?php   
    if($_POST){  
        $fact = 1;  
        //getting value from input text box 'number'  
        $number = $_POST['number'];  
        echo "Factorial of $number:<br><br>";  
        //start loop  
        for ($i = 1; $i <= $number; $i++){         
            $fact = $fact * $i;  
            }  
            echo $fact . "<br>";  
    }  
?>  
</body>  
</html>

    

Output


Factorial using Recursion in PHP

Factorial of 6 using recursion method is shown.

Example:

                    
<?php
function fact ($n)  
{  
    if($n <= 1)   
    {  
        return 1;  
    }  
    else   
    {  
        return $n * fact($n - 1);  
    }  
}  
  
echo "Factorial of 6 is " .fact(6);
?>  
    

Output