这是我的PHP代码
<?php
$i = 2;
$primes = array();
while(true)
{
$prime=true;
$sqrt=floor(sqrt($i));
foreach($primes as $num)
{
if($i%$num==0)
{
$prime=false;
break;
}
if($num>$sqrt) break;
}
if($prime) echo "$i\n";
$i++;
}
这是运行它的小bash脚本
#!/bin/bash
outfile="$1.out"
`php $1 > $outfile &`
sleep 60
killall php
修改
这是昨晚的pcntl_forked版本,只是为了看看会更快。
出于一些奇怪的原因,我做得越少越好,如果是,我发现了
瓶颈来自gmp_strval(gmp_nextprime($start))
,这非常缓慢。
<?php
$primeCount = 0;
for ($i = 1; $i <= 1; ++$i) {
$start = $i;
$pid = pcntl_fork();
if (!$pid) {
while(true) echo $start = gmp_strval(gmp_nextprime($start)) . "\n";
exit($i);
}
}
while (pcntl_waitpid(0, $status) != -1) {
$status = pcntl_wexitstatus($status);
#echo "Child $status , $primeCount completed\n";
}
die;
答案 0 :(得分:8)
除了2和3之外,所有素数都是高于6的倍数或者低于6的倍数。这应该将搜索空间减少到大约1/3而不是每次增加1。用2,3筛选筛子并使用缩小的搜索空间来加快时间。
如果您需要简单解释其工作原理:
1 + n*6 (This is one above, and I state it's got primes)
2 + n*6 (multiple of 2)
3 + n*6 (multiple of 3)
4 + n*6 (multiple of 2)
5 + n*6 (This is one below, and I state it's got primes)
6 + n*6 (multiple of 2,3,6)