Factorial Program in PHP Using for Loop and While Loop

factorial of a number in php
Factorial of a number in PHP

Today we are going to find out factorial of a number in PHP. We have discussed and shared how to find Prime Numbers in PHP in our earlier posts. So we will try to be to the point as much as possible.

factorial of a number in php

Factorial of a number in PHP

To know how to find out factorial of a number in C, Python or PHP you have to know what is a factorial. So first of all we are going to tell you what is a factorial in Mathematics?

What is a factorial?

In the past times factorials were used to count permutations in 12th century by Indian scholars. It is still used in Combinations and Permutations in Mathematics today as well. It is used to solve problems like how many ways can 7 people come 1st, 2nd and 3rd? etc.

  • Factorial is a product of an integer and all the integers less than the integer except 0.
  • The factorial of a number n is the product of all the digits from 1 to n (1 and n inclusive) and it is written as n!.
  • The factorial of a non-negative integer n written as n!, is the product of all positive numbers less than or equal to n.

The 0 factorial

The factorial of 0 or 0 factorial is always equal to 1 according to the convention for an empty product.

In mathematical terms 0! = 1.

The factorial of 1 or 1! is equal to 1 as well.

Factorial Examples

The 4 factorial:

4! = 1x2x3x4

4! = 24.

The 5 factorial:

5! = 1x2x3x4x5

5! = 120.

Now as we understood what is a factorial in Mathematics? now we are able to write a function to get factorial of an integer in PHP. So here are some functions to find factorial in PHP. These functions can also be used in other languages such like write factorial program in C, Python or Java after changing accordingly.

Factorial program in php using for loop

<?php
	
	function factorail ($x) {  

	    if($x <= 1) {  
	        return 1;  
	    }else{  
	        return $x * factorail($x - 1);  
	    }  
	}  
  
	echo "Factorial of 5 is " .factorail(5)."
";  
?>

Factorial of a number in PHP using for loop:

<?php 
	function factorial($x){ 
	    if($x <= 1){   
	        return 1;   
	    }   
	    else{   
	        return $x * factorial($x - 1);   
	    }   
	} 
	  
	$x = 4; 
	$fact = factorial($x); 
	echo "Factorial of 4 = $fact
";
?> 

Factorial of a number in PHP using while loop

<?php 
	$x = 5;
	$factorial = 1;
	do {
	  $factorial *= $x;
	  $x = $x - 1;
	} while ($x > 0);
	echo "Factorial of 5 = ".$factorial;
?>

You would love to read Prime Number Program in PHP as well.

Comments