PHP | Factorial of a number

We already know how to get the factorial of a number in other languages. Let’s see how this is done in PHP using both recursive and non-recursive ways.

Examples:

Input : 5
Output : 120

Input : 10
Output : 3628800

Method 1: Iterative way
In this method, we simply used the for loop to iterate over the sequence of numbers to get the factorial.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP code to get the factorial of a number
// function to get factorial in iterative way
function Factorial($number){
    $factorial = 1;
    for ($i = 1; $i <= $number; $i++){
      $factorial = $factorial * $i;
    }
    return $factorial;
}
  
// Driver Code
$number = 10;
$fact = Factorial($number);
echo "Factorial = $fact";
?>

chevron_right


Output:

3628800

Method 2: Use of recursion
In this method we are calling the same method to get the sequence of the factorial.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP code to get the factorial of a number
// function to get factorial in iterative way
function Factorial($number){
    if($number <= 1){  
        return 1;  
    }  
    else{  
        return $number * Factorial($number - 1);  
    }  
}
  
// Driver Code
$number = 10;
$fact = Factorial($number);
echo "Factorial = $fact";
?>

chevron_right


Output:

3628800


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.