Skip to main content

Factorial

The factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1.

Examples:

  • 4! = 4 × 3 × 2 × 1 = 24
  • 7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
  • 1! = 1

Wikipedia.

PHP: using gmp_fact function

A native PHP function called gmp_fact is available and it calculates the factorial of a number:


echo gmp_fact(5);

PHP: creating a recursive function


// Formula: n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1.
function factorial($n)
{
   if ($n == 0)
       return 1;
   else
       return($n * factorial($n - 1));
}

echo factorial(5);

JAVA: simple for cycle


class Factorial {
   public static void main(String args[]){  
       int i,fact=1;
       int number=5;// It is the number to calculate factorial
       for(i=1; i<=number; i++) {
           fact=fact*i;
       }
       System.out.println("Factorial of "+number+" is: "+fact);    
   }
}

Javascript recursive function


var f = [];
function factorial (n) {
 if (n == 0 || n == 1)
   return 1;
 if (f[n] > 0)
   return f[n];
 return f[n] = factorial(n-1) * n;
}
console.log( factorial(4) ); // 24