PHP code to print the factorial of a number

Below is the php code to print the factorial of a number.

$save_factorial=array();
function factorial($n)
{
    global $save_factorial;
    if($n==1||$n==0)
        return 1;
    if(isset($save_factorial[$n]))
        return $save_factorial[$n];
    $save_factorial[$n]=bcmul($n,factorial($n-1));
        return $save_factorial[$n];
}

$t=trim(fgets(STDIN));
for($k=1;$k<=$t;$k++)
{
    $i=trim(fgets(STDIN));
    echo factorial($i)."\n";
}

No comments:

Post a Comment