PHP Program - Find Factorial of a Number
The factorial of a positive integer is the multiplication of all positive integer less than or equal to that number.
factorial of number n = n! = n(n-1)(n-2)...1
For Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
4! = 4 × 3 × 2 × 1 = 24
Method 1: Using Recursive method
In the example below, a recursive function called factorial() is used to calculate factorial of a number.
<?php function factorial($x) { if ($x == 0 || $x == 1) return 1; else return $x*factorial($x-1); } echo "10! = ".factorial(10)."\n"; echo "6! = ".factorial(6)."\n"; ?>
The above code will give the following output:
10! = 3628800 6! = 720
Method 2: Using Iterative method
The factorial of a number can also be calculated using iterative method.
<?php function factorial($x) { $finalnum = 1; for($i = $x; $i > 0; $i--) { $finalnum = $finalnum * $i; } return $finalnum; } echo "10! = ".factorial(10)."\n"; echo "6! = ".factorial(6)."\n"; ?>
The above code will give the following output:
10! = 3628800 6! = 720
Method 3: Using Ternary Operator
In the example below, the factorial of a number is calculated using ternary operator.
<?php function factorial($x) { $y = ($x == 0 || $x == 1)? 1 : $x*factorial($x-1); return $y; } echo "10! = ".factorial(10)."\n"; echo "6! = ".factorial(6)."\n"; ?>
The above code will give the following output:
10! = 3628800 6! = 720
Recommended Pages
- PHP Program - To Check Prime Number
- PHP Program - Bubble Sort
- PHP Program - Selection Sort
- PHP Program - Maximum Subarray Sum
- PHP Program - Reverse digits of a given Integer
- PHP Program - Merge Sort
- PHP Program - Shell Sort
- Stack in PHP
- Queue in PHP
- PHP Program - Find LCM of Two Numbers
- PHP Program - To Check Whether a Number is Palindrome or Not
- PHP Program - To Check Whether a String is Palindrome or Not
- PHP Program - Heap Sort
- PHP Program - Quick Sort
- PHP - Swap Two Numbers without using Temporary Variable
- PHP Program - To Check Armstrong Number
- PHP Program - Counting Sort
- PHP Program - Radix Sort
- PHP Program - Find Largest Number among Three Numbers
- PHP Program - Print Floyd's Triangle