Tuesday, 13 May 2014

To Find The Factorial Of A Number Using PHP

A factorial of a number n is the product of all the numbers between n and 1.
The easiest way to calculate it is with a for( )
loop which one that starts at n and counts down to 1. Each time the loop runs,
the previously calculated product is multiplied by
the current value of the loop counter and the result is the factorial of the number n.


To find the factorial number, you can use a loop to count down and multiply the number by all the numbers between itself and 1 such as:

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

Output will be :

4
3
2
1
Factorial of 4 is 24

To find the factorial of a number using form in php

index.php

<?php
/* Function to get Factorial of a Number */
function getFactorial($num)
{
    $fact = 1;
    for($i = 1; $i <= $num ;$i++)
        $fact = $fact * $i;
    return $fact;
}
?>
<!doctype html>
<html>
<head>
<title>Factorial Program using PHP</title>
</head>
<body>
<form action = "" method="post">
Enter the number whose factorial requires <Br />
<input type="number" name="number" id="number" maxlength="4" autofocus required/>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']) and $_POST['submit'] == "Submit")
{
    if(isset($_POST['number']) and is_numeric($_POST['number']))
    {
        echo 'Factorial Of Number: <strong>'.getFactorial($_POST['number']).'</strong>';
    }
}

?>
</body>
</html>


 Output will be :

if you enter 5 and click to submit then :

Enter the number whose factorial requires 
 
Factorial Of Number: 120


 

No comments:

Post a Comment

Printing first 50 Fibonacci numbers Using PHP Program

Fibonacci series is a series of numbers in which each number is the sum of the two preceding numbers. For example. 0 , 1 , 1 , 2 , 3 , 5...