php谜语-有趣的结果

php谜语-有趣的结果,php,logic,Php,Logic,我有以下代码: <?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){

我有以下代码:

<?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}, ";
    }
}

?>
如您所见,它输出正方形。 我认为这一现象令人印象深刻,但我对数学解释感兴趣-

为什么会出现这种模式


谢谢

对于每个独特的因素,您都会翻转一次状态


正方形有奇数个唯一因子。

它是这样工作的,因为这是经典的。。。在locker问题中,只返回因子为奇数的数。。。这些都是正方形。

我在评论中逐条说明:

<?php

$cups = array();
for($i=0; $i<500; $i++){
    $cups[$i] = 0;
}
// fill up indices 1-500

// at this step you set up the loop, and increment x
for($x=1; $x<500; $x++){
// since $x is now 2, you are actually looping from 2 to 500, and
// adding 2 to every iteration of $y
    for($y=$x; $y<500; $y+=$x){
 // now you're only showing a value if theyre not the same
    $cups[$y] = !$cups[$y];
    }
}

foreach($cups as $key => $value){
    // here you only loop through those with a value (which is every value + 2) 
    // you are basically counting by 2s (2, 4, 
    if($value == 1){
        echo "{$key}, ";
    }


}
等等


我相信有人会比我解释得更准确、更简洁,但这让你对这里发生的事情有了一些了解

无论是谁把这标记为“不是真正的问题”——我的问题是为什么会出现这种模式?“与编程无关”会更合适。这是一个简单的数学问题:自然数有成对的因子,除了平方数,其中一个因子出现两次,但循环只计算一次。我+1这一个,因为它在转化为软件时是一个有趣的问题,这使得它与编程相关。你是在找我还是什么?:)你能详细说明一下吗?如果你把每个数字分解成唯一的因子,所有的因子都是2,它们是不同的。。。除了平方数。例1:20=(1*20)或(2*10)或(5*4)。例2:16=(1*16)或(2*8)或(4*4)
<?php

$cups = array();
for($i=0; $i<500; $i++){
    $cups[$i] = 0;
}
// fill up indices 1-500

// at this step you set up the loop, and increment x
for($x=1; $x<500; $x++){
// since $x is now 2, you are actually looping from 2 to 500, and
// adding 2 to every iteration of $y
    for($y=$x; $y<500; $y+=$x){
 // now you're only showing a value if theyre not the same
    $cups[$y] = !$cups[$y];
    }
}

foreach($cups as $key => $value){
    // here you only loop through those with a value (which is every value + 2) 
    // you are basically counting by 2s (2, 4, 
    if($value == 1){
        echo "{$key}, ";
    }


}
1  + 3 = 4
4  + 5 = 9
9  + 7 = 16
16 + 9 = 25