PHP Function To Work Out Factorial Numbers

8th October 2008 - 2 minutes read time

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.

  1. function factorial($number){
  2. $result = 1;
  3. if($number > 1){
  4. for($i = 2; $i <= $number; $i++){
  5. $result *= $i;
  6. }
  7. }
  8. return $result;
  9. }

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

Permalink

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

sofi morris (Wed, 03/10/2021 - 00:23)

Permalink

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

Add new comment

The content of this field is kept private and will not be shown publicly.