This blog describes about how to find factorial of given number in PHP. The factorial is one of the maths concept. It is multiplication of numbers from 1 to given number. If the given number defined as 'n', then 'n' factorial represented as 'n!'. The factorial formula for 'n' number looks like:
n! = 1 * 2 * 3 ... n;
For example, the factorial of 5 looks like this:
5! = 1 * 2 * 3 * 4* 5 = 120;
Consider the below example which is the sample PHP program for find factorial of number:
Where,
'n' is 4.
n! = 4! = 1 * 2 * 3 * 4 = 24.
n! = 1 * 2 * 3 ... n;
For example, the factorial of 5 looks like this:
5! = 1 * 2 * 3 * 4* 5 = 120;
Simple PHP program for Factorial:
Consider the below example which is the sample PHP program for find factorial of number:
function factorial($a) {
$fact = 1;
for($i = 1; $i <= $a; $i++) {
$fact = $fact * $i;
}
return $fact;
}
$f = factorial(4);
echo $f;
$fact = 1;
for($i = 1; $i <= $a; $i++) {
$fact = $fact * $i;
}
return $fact;
}
$f = factorial(4);
echo $f;
Where,
'n' is 4.
n! = 4! = 1 * 2 * 3 * 4 = 24.
Factorial for 'n' number in PHP:
Consider the below example which is the PHP program for find factorial of given number. For example, if you enter 4, it will return factorial of 4. Like if you enter 'n' number, it will return factorial of 'n'.
<html>
<head>
<style type="text/css">
body {
color:white;
font-size:14px;
}
.contact {
text-align:center;
background: none repeat scroll 0% 0% #8FBF73;
padding: 20px 10px;
box-shadow: 1px 2px 1px #8FBF73;
border-radius: 10px;
width:520px;
}
#number {
width: 250px;
margin-bottom: 15px;
background: none repeat scroll 0% 0% #AFCF9C;
border: 1px solid #91B57C;
height: 30px;
color: #808080;
border-radius: 8px;
box-shadow: 1px 2px 3px;
padding: 3px 4px;
}
#submit
{
background:none repeat scroll 0% 0% #8FCB73;
display: inline-block;
padding: 5px 10px;
line-height: 1.05em;
box-shadow: 1px 2px 3px #8FCB73;
border-radius: 8px;
border: 1px solid #8FCB73;
text-decoration: none;
opacity: 0.9;
cursor: pointer;
color:white;
}
#er {
color: #F00;
text-align: center;
margin: 10px 0px;
font-size: 17px;
}
</style>
</head>
<body>
<div class="contact">
<h1>Factorial in PHP</h1>
<form action="#" method="POST">
Enter number : <input type="text" name="number" id="number" /></br>
<input type="submit" name="submit" id="submit" value="Submit"></input>
</form>
<?php
if(isset($_POST['submit'])) {
$n = $_POST['number'];
function factorial($a) {
$fact = 1;
for($i = 1; $i <= $a; $i++) {
$fact = $fact * $i;
}
return $fact;
}
$f = factorial($n);
echo "<div class=''>Factorial of $n is $f</div>";
}
?>
</div>
</body>
</html>
When you open above program in browser, it looks like this:
Whatever you enter number in the textbox, it returns factorial of given number.