Factorial not given "out of range" if value less than -1

Viewed 25

Code gives me "out of range "if the value greater than 20, but not give me "out of range " if value less than -1

<?php
$number = -1;
$factorial = 1;
for ($i = $number; $i > 0; $i--) {
$factorial = $factorial * $i;
if ($number > 20 || $number <= 0) {
      exit('out of range');
}
}
echo "the factorial of $number is: ".$factorial;
1 Answers

The reason this happens is because of how you have structured your for loop.

You set the initial value $i = -1, but then you check the condition $i > 0. Because it is less than 0, the loop never executes.

To make it work, you need to put the out of bounds check before the for loop.

$number = -1;
$factorial = 1;

if ($number > 20 || $number <= 0) {
    exit('out of range');
}

for ($i = $number; $i > 0; $i--) {
    $factorial = $factorial * $i;
}

echo "the factorial of $number is: " . $factorial;
Related