Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php riddle - interesting result

Tags:

php

logic

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!

like image 368
Yuval Karmi Avatar asked Feb 04 '26 12:02

Yuval Karmi


1 Answers

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.

like image 155
Powerlord Avatar answered Feb 07 '26 03:02

Powerlord



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!