How to calculate the factorial of a number?

Asked

Viewed 4,614 times

0

I have tried, tried and nothing. A program that multiplies a number typed by someone in descending order.

For example:

typed 7 and I gave OK: 7x6x5x4x3x2x1

should be the result of all this.

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>";
    }
?>  

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.

2

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

Behold:

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

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

Exit:

5040

More information in this answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.