Guess number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
$secretNum = rand(1, 100); // 90.
$minNum = 1;
$maxNum = 100;
$divider = floor($maxNum / 2); // 100 / 2 = 50
$guessNum = $divider; // 50.
$isNumberFound = false;
$stages = 1;
while (!$isNumberFound) {
$divider = (floor($divider / 2)) > 1 ? floor($divider / 2) : ceil($divider / 2);
//$divider = floor($divider / 2); // 1 / 2 = 0.
if ($guessNum == $secretNum) { // 46 === 46.
echo "Your number is {$guessNum}. The secret is {$secretNum}. Stages in sum: {$stages}.";
$isNumberFound = true;
} else if ($guessNum > $secretNum) {
echo "Search lower. Your number is {$guessNum}. The secret is {$secretNum}.";
echo "<br>";
$guessNum -= $divider; // guessNum = 50 - 25 = 25.
} else {
echo "Search higher. Your number is {$guessNum}. The secret is {$secretNum}.";
echo "<br>";
$guessNum += $divider; // guessNum = 43 + 3 = 46.
}
$stages++;
}
?>