It is what we call the neutral element of the operation.
That value, $fat = 1
, will always be there regardless of what the input value is, that is, whether we are calculating the factorial of 5 or 345; $fat
will always start with the value 1.
Why exactly the 1?
Because we need to ensure that this initial value does not interfere in any way with our result and, for this, we assign as initial value the neutral value of multiplication.
The neutral value, X
, of an operation is that when the operation is performed the result is the other operand. For example, X * A
needs to be A
why X
is considered the neutral element. Only if X = 1
the result will be A
, regardless of the value of A
.
The same happens with the value 0 when the mathematical operation is the addition, because 0 + A
will always be A
, regardless of the value of A
.
In this way, starting $fat = 1
, we guarantee that when executed $fat = $fat * $c
the result will be $c
regardless of the value of $c
.
Factorial of a number is the multiplication of it by all its predecessors greater than zero. The fact of using
$fat
like 1, it does not require auxiliary variables to calculate, because the factorial is calculated using only the variable $fat and the initial number ($c) or its predecessor ($c-) at each iteration. If$fat
had no value, would be considered zero, the product of zero is zero. The condition could still be$c > 1
, no need to multiply by 1. Moreover, the order of the factors do not change the product.– Gabriel Heming
but the fat value has to be different from 1 to multiply with $c in the $fat = $fat * $c
– matheusdouradobr
What you just said makes no sense. Do a table test by iteration, it will be easy to understand. Let’s say I make the factorial of 5. First iteration is (
$fat = 1 * 5 -> 5
), second$fat = 5 * 4 -> 20
, third$fat = 20 * 3 -> 60
, fourth and final$fat = 60 * 2 -> 120
. If you do not use it as shown, you will need to use auxiliary variables for the factorial value and what is the current value$fat = 1
is just one of the many forms of logic that can be employed.– Gabriel Heming
Reinforcing what @Gabrielheming said and responding with a super simple phrase: because it’s the neutral element of multiplication
– Isac
if $fat starts with 1, where it is written in the code the value for it to multiply with $c, if it is factorial of $c = $v, if $v is equal to the chosen value let’s assume 3, ai $c = $v = 3 ai becomes $fat = 1 (starts with value 1) ai then $fat = $fat * $c (on this line as php assigns a value other than 1 to $fat?) to bugando on this part between parentheses rs
– matheusdouradobr
In that case it begins with
$fat = 1 * 3
which gives 3. Remember that any number multiplied by 1 gives the number itself and that is why 1 is the neutral element of multiplication.– Isac