PHP Function To Work Out Factorial Numbers

Factorial of a number is defined as the product of the number and all of the numbers small than it. So if you take the number 4 the factorial of that number is 24 or 1 x 2 x 3 x 4.

Factorials are useful for a number of applications, for example when working out how many times a set of objects can be combined in different ways.

Use the following PHP function to work out the factorial of any given number. The first thing it does it make sure that the number is greater than 1 because the factorial of the number 1 is 1.


function factorial($number){
 $result = 1;
 if($number > 1){
  for($i = 2; $i <= $number; $i++){
   $result *= $i;
  }
 }
 return $result;
}

The function works by using the *= operator, which does a calculation between the left and right sides (in this case multiplication) and stores the result on the left hand side. This operator is much like the += operator, and works in the same way.

An alternative of this is the GMP function gmp_fact(). GMP is a set of maths functions that can be used to do some special things like add very large numbers together. It has been part of the PHP core since version 4.0.4.

Beware that factorial numbers can get very large, very quickly. For example, the factorial of the number 50 is 30,414,093,201,713,375,576,366,966,406,747,986,832,057,064,836,514,787,179,557,289,984. Calculating a number this large is not possible without using the GMP functions, but not only that, it will also take a while to calculate it.

Comments

Hello Philip,

I don't think you are keeping track of your article.

We are now 2021, your article was written in 2008 =13 years

Permalink

I'm not sure what you mean Sofi. I have been writing on this blog for around 14 years at this point.

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.