How to calculate the factorial of a number?

1

I've tried, tried, and nothing. A program that multiplies a number entered by someone in descending order.

For example:

I typed 7 and gave OK: 7x6x5x4x3x2x1

The result of all this should appear.

Code I already have:

<?php

    $n = $_GET['num'];
    $n2 = $n1;
    $tot = 0;

    while($n >= 1){
        $n2 = $n2 - 1;
        $tot = $n2 * $n2;
        $n--;
        echo "$tot <br>";
    }
?>  
    
asked by anonymous 27.09.2017 / 18:46

2 answers

3

So you want to calculate the factorial of a number:

    $i = $_GET['num'];
    $calc = 1;
    while ($i > 1){
        $calc *= $i;
        $i--;
    }

    echo $calc;

In mathematics, the factorial of a natural number n, represented by n !, is the product of all positive integers less than or equal to n.     

27.09.2017 / 18:57
2

If you want to calculate the factorial of a number, you can use the array_product function to calculate the product of the values contained in the array that in this case would be the sequence generated by the range() function.

See:

$numero = 7; //Pode vir de um GET ou POST

$v = array_product(range($numero, 1));
print_r($v);

Output:

  

5040

More information in this answer .

    
27.09.2017 / 19:13