mercredi 29 juin 2016

PHP 7 "for loop" bug with if statement. Stops working after 32.767 loops?

I`ve been playing around with PHP and tried to find this "bug" fix, but could not find anything about it...

The Task: Find out how many tries it takes to discover a random selected number.

I generated a random number outside a for loop and declared a variable that will be the maximum amout of times the for loop will run to try and guess this number. If the random number generated inside the for loop is "==" to the number generated outside the loop I save that number in a variable, save the amout of times it took to get it right and break out of the loop... Simple stuff.

THE "BUG":

Evertything works great, until we get up to 32.767 times inside the for loop.. If we work with small numbers nothing goes wrong, but if we try some big random numbers, like above 50.000, the if statement inside the for loop will execute on the 32.767th time, no matter what. It`s like the "==" sundently turns into a "=".

Beeing new to PHP I thought this could be a memory thing, but I tried out some big loops without the if statement and they all worked...

Here is the code:

<?php

$number = rand(1,50000); // Change this to something small, bellow 30.000, and it will start to work. make it the same as line 10.
$correctNumber;
$maximumLoops = 50000; // No matter how much loops you try, if the random number is big and we get to the 32.767th loop, the if statement will execute.
$numberOfLoops = 0;


for($i = 0; $i < $maximumLoops; $i++){
    $randNumber = rand(1,50000); // Change this to something small, bellow 30.000, and it will start to work. make it the same as line 3.
    if($randNumber == $number){
        $correctNumber = $number;
        $numberOfLoops = $i;
        break;

    }
}

echo "The Number was: $number<br>";
echo "Correct Number is: $correctNumber<br>";
echo "The maximum number of loops was: $maximumLoops<br>";
echo "Number of loops to get it right: $numberOfLoops";

Any help would be greatly appreciated. Thanks

Aucun commentaire:

Enregistrer un commentaire