What is Factorial ?

The factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1.
Examples:
4! = 4 x 3 x 2 x 1 = 24
5! = 5 x 4 x 3 x 2 x 1 = 120
6! = 6 x 5 x 4 x 3 x 2 x 1 =720
7! = 7 x 6 x 5 x 4 x 3 x 2 x 1 = 5040

Programs Functions

//Method 1	
function factorial_1($number) {
		//Using For Loop
		$factorial = 1;
		for ($number = $number; $number > 0; $number--) {
			$factorial = $factorial * $number;
		}
		return $factorial;
	}
//Method 2
	function factorial_2($number) {
		//Using While Loop
		$factorial = 1;
		while ($number > 0) {
			$factorial = $factorial * $number;
			$number--;
		}
		return $factorial;
	}
//Method 3
	function factorial_3($number) {
		//Short While Loop
		$factorial = 1;
		while ($number != 1) {
			$factorial *= $number;
			$number--;
		}
		return $factorial;
	}
//Method 4
	function factorial_4($number) {
		// Using single line
		return ($number == 1 || $number == 0) ? 1 : $number * factorial_4($number - 1);
	}
//Method 5
	function factorial_5($number) {
		//Using Without Loop
		if ($number == 0)
			return 1;
		else {
			$factorial = $number * factorial_5($number - 1);
			return $factorial;
		}
	}

Method  1

	//Method 1
	function factorial_1($number) {
		//Using For Loop
		$factorial = 1;
		for ($number = $number; $number > 0; $number--) {
			$factorial = $factorial * $number;
		}
		return $factorial;
	}
	echo factorial_1(7);
//5040

 

Method  2

	//Method 2
	function factorial_2($number) {
		//Using While Loop
		$factorial = 1;
		while ($number > 0) {
			$factorial = $factorial * $number;
			$number--;
		}
		return $factorial;
	}
	echo factorial_2(7);
//5040

Method  3

	//Method 3
	function factorial_3($number) {
		//Short While Loop
		$factorial = 1;
		while ($number != 1) {
			$factorial *= $number;
			$number--;
		}
		return $factorial;
	}
	echo factorial_3(7);
//5040

Method  4

	//Method 4
	function factorial_4($number) {
		// Using single line
		return ($number == 1 || $number == 0) ? 1 : $number * factorial_4($number - 1);
	}
	echo factorial_4(7);
//5040

Method  5

	//Method 5
	function factorial_5($number) {
		//Using Without Loop Or Recursive Formula

		if ($number == 0)
			return 1;
		else {
			$factorial = $number * factorial_5($number - 1);
			return $factorial;
		}
	}
	echo factorial_5(7);
//5040

Demo Program

SEE WORKING

If You Know Any Different Way To Find Factorial Please Comment Us.

(Visited 128 times, 1 visits today)
Share with Friends :
Written by:

Leave a Reply

Your email address will not be published. Required fields are marked *