PHP program for factorial

The factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1.

i.e
2! = 2*1 =2
3! = 3*2*1= 6
5! = 5*4*3*2*1 = 120

So maths rules is n! = n × (n−1)!

Factorial of 0 is always 1.

How to Find Factorial in PHP?

There are two ways to find factorial in PHP as below.

1. Using Loop : We will use for loop to iterate over the sequence of numbers to get the factorial.
2. Using recursive method : We will call the same method to get the sequence of the factorial.

Lets see below example to find factorial  for number using form in php.

 

 

 

Example :

<?php
$result="";
function find_factorial($number){
if($number <= 1){
return 1;
}
else{
return $number * find_factorial($number - 1);
}
}

if(isset($_POST['submit']))
{

$num=$_POST['num'];


// PHP code to get factorial using method recursion

$fact_num = find_factorial($num);
$result .= "<br/>Factorial Number for $num! using recursion method is $fact_num";

// PHP code to get the factorial of a number using for loop
for ($i = 1; $i <= $num; $i++){
$factorial = $factorial * $i;
}

$result .= "<br/>Factorial Number for $num! using loop is $fact_num";

}

?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Maths Program - Find factorial by aryatechno</title>
</head>
<body>
<table>
<form name="find" method="post">
<tr>
<td colspan="2"><strong>Find factorial program</strong></td>
</tr>
<tr>
<td>Enter Number :</td>
<td><input type="text" name="num" value="<?=$_POST['num'] ?>" required></td>
</tr>

<tr>
<td></td>
<td><input type="submit" value="Find factorial" name="submit" /></td>
</tr>
<tr>
<td colspan="2"><strong><?=$result ?></strong></td>
</tr>

</form>
</table>
</body>
</html>

Output :

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

30853