In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
For example, 5! = 5 x 4 x 3 x 2 x 1 = 120
The value of 0! is 1, according to the convention for an empty product.
To know more about factorial, click here.

"My version of non-integer factorial"

<?php
// For example, 5! = 5 x 4 x 3 x 2 x 1 = 120
$f = $temp1 = $temp2 = 5;
while ( --$temp2 > 0) {
  $temp1 *= $temp2;
}
echo $f . '! = ' . (($f>=0) ? (($f==0) ? 1 : $temp1) : '');
// The output is: 5! = 120
?>

Explaination

1. Equate integer 5 to the three different variables $f, $temp1 and $temp2
$f = $temp1 = $temp2 = 5;

2. Condition of while loop. At the first place the server will pre-decrement ($temp2 = $temp2 - 1) the variable $temp2 before it checks if $temp2 is greater than 0 ($temp2 > 0).
while ( --$temp2 > 0) {
// statement here
}

3. While the condition is true $temp1 = $temp1 * $temp2
  $temp1 *= $temp2;

4. After the loop,it will print the $f and concatenate to string '! = ' then concatenate to ternary result. If (($f>0) ? TRUE : FALSE), if it is TRUE, it will proceed to 2nd ternary which is (($f==0) ? 1 : $temp1 ), if $f==0, the result is 1 else simply $temp1. If the 1st ternary turns to FALSE, it will concatenate to empty string.
echo $f . '! = ' . (($f>=0) ? (($f==0) ? 1 : $temp1) : '');

And that is my version of non-integer factorial.



July 19, 2011   |   Blog   |   Add Comment   |   3 Comments

Did you like this article? Share it to others.

facebook twitter stumbleupon digg delicious reddit

3 Comments to "Factorial using PHP"

Comment February 7, 2012 at 11:07am
Bayo says:


I really appreciate your php code for the factorial. please, do me a favour. I need a php code that can calculate n value of any number and not just 5!. I want a situation where users can be asked to put in a figure into the form and the factorial is calculated. thanks very much in advance.

Comment February 7, 2012 at 11:18am
Carlson Orozco says:


Thanks for your message Bayo.. I created a simple user input factorial using php and html.. Check out this link.. then save this as php file to your host.

Comment February 15, 2012 at 9:23am
Bayo says:


I must really thank you for the php code once again. I found very useful and I am saying God blessing to you. thanks very much.

Post Comment