Why does $ fat start with 1 in the factorial calculation?

0

Why in this code does $fat start with 1?

Is a code to find the factorial of a number ( $v = valor ):

<?php
    $v = isset($_GET["valor"])?$_GET["valor"]:1;
    echo "<h1>Calculando o fatorial de $v</h1>";
    $c = $v;
    $fat = 1;
    do {
        $fat = $fat * $c;
        $c--;
    } while ($c>=1);
    echo "<h2>$v! = $fat</h2>";
?>

The code can also be viewed here .

    
asked by anonymous 30.10.2018 / 20:21

1 answer

1

This is what we call the neutral element of the operation.

This value, $fat = 1 , will always be there regardless of the input value, that is, if we are calculating the factorial of 5 or 345; $fat will always start with value 1.

Why exactly 1?

Because we need to ensure that this initial value does not interfere in any way with our result, and for this we assign the neutral value of the multiplication as the initial value.

The neutral value, X , of an operation is that when the operation is performed the result is the other operand. For example, X * A must be A so that X is considered the neutral element. Only if X = 1 the result will be A , independent of the value of A .

The same happens with the value 0 when the mathematical operation is the addition, since 0 + A will always be A , independent of the value of A .

In this way, starting $fat = 1 , we guarantee that when $fat = $fat * $c is executed the result will be $c independent of the $c value.

    
14.01.2019 / 19:41