Jul
19
19
Factorial using PHP
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.
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).
3. While the condition is true $temp1 = $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.
And that is my version of non-integer factorial.
Tweet
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.







Contact Me!

Latest Blog Post
3 Comments to "Factorial using PHP"