Q:

Find factorial of a number in PHP

belongs to collection: PHP Basic Programs

0

Given a number and we have to find its factorial.

Formula to find factorial: 5! (Factorial of 5) = 5x4x3x2x1 = 120

Example:

    Input: 5
    Output: 120

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find factorial of a number in PHP

<?php
    //program to find factorial of a number
    //here, we are designing a function that
    //will take number as argument and return
    //factorial of that number
    
    //function: getFactorial
    function getFactorial($num){
        //declare a variable and assign with 1
        $factorial = 1;
        for($loop = 1; $loop <= $num; $loop++)
            $factorial = $factorial * $loop;
        return $factorial;
    }

    //Main code to test above function
    $number = 1;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
    $number = 2;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
    $number = 3;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
    $number = 4;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");  
    $number = 5;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");    
?>

Output

Factorial of 1 is = 1
Factorial of 2 is = 2
Factorial of 3 is = 6
Factorial of 4 is = 24
Factorial of 5 is = 120

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Calculate difference between dates in PHP... >>
<< Check Even and ODD in PHP...