Encuentra factorial de un número en PHP

En este artículo, vamos a aprender cómo encontrar factorial de un número determinado mediante el programa PHP ?

Dado un número y tenemos que encontrar su factorial.

fórmula para hallar factorial: 5! (Factorial de 5) = 5x4x3x2x1 = 120

Ejemplo:

    Input: 5
Output: 120

programa para encontrar factorial de un número en 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");
?>

salida

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


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *