Search code examples
phplogic

php riddle - interesting result


I have the following code:

<?php

$cups = array();
for($i=0; $i<500; $i++){
    $cups[$i] = 0;
}

for($x=1; $x<500; $x++){
    for($y=$x; $y<500; $y+=$x){
        $cups[$y] = !$cups[$y];
    }
}

foreach($cups as $key => $value){
    if($value == 1){
        echo "{$key}, ";
    }
}

?>

As you can see, I fill up an array with 500 zeroes, loop through it twice, and then print out the cup numbers that have a '1' in them:

1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484,

As you can see - it outputs squares. I think the phenomenon is impressive, but I am interested in a mathematical explanation -

Why does this pattern occur?

Thanks!


Solution

  • It works this way because this is the classic Locker Problem... and in the locker problem, only the numbers with odd number of factors are returned... which are all the squares.