php谜语 - 有趣的结果

时间:2009-11-17 20:49:44

标签: 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){
        echo "{$key}, ";
    }
}

?>

正如您所看到的,我填充了一个包含500个零的数组,循环两次,然后打印出其中包含“1”的杯号:

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

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

为什么会出现这种模式?

谢谢!

3 个答案:

答案 0 :(得分:8)

它以这种方式工作,因为这是经典的Locker Problem ...而在更衣柜问题中,只返回具有奇数个因子的数字......这些都是正方形。

答案 1 :(得分:4)

嗯,你正在为每个独特的因素翻转一次状态。

正方形具有奇数个独特因子。

答案 2 :(得分:2)

我在评论中将游戏放在游戏中:

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


}

基本上你要创建的是具有奇数因子的数字列表,它们是正方形。

注意每个值如何以值+ 2的顺序递增:

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

等等。

我确信有人会比我更准确,更简洁地解释它,但是这会让你知道这里发生了什么。