筛法找质数之PHP版

下面的程序会找出 1000000 以内的所有质数。

define(‘MAX_NUM’, 1000000);
$all = array_fill(0,MAX_NUM,0);
for ($i = 2; $i < MAX_NUM; $i++) {    
    if ($all[$i] == 0) {
        echo $i,”n”;  //测试性能时去掉这行。输出会占据大部分时间。
        for ($j = $i; $j < MAX_NUM; $j+=$i) {
            $all[$j] = 1;
        }
    }
}

2 thoughts on “筛法找质数之PHP版

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.