PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: simple factorial program

## Pages

simple factorial program - phponwebsites.com
Showing posts with label simple factorial program. Show all posts

# Factorial of given number in PHP

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;

### 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;

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>
<style type="text/css">
body {
color:white;
font-size:14px;
}
.contact {
text-align:center;
background: none repeat scroll 0% 0% #8FBF73;
width:520px;
}
#number {
width: 250px;
margin-bottom: 15px;
background: none repeat scroll 0% 0% #AFCF9C;
border: 1px solid #91B57C;
height: 30px;
color: #808080;
}
#submit
{
background:none repeat scroll 0% 0% #8FCB73;
display: inline-block;
line-height: 1.05em;
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>
<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.