【发布时间】:2014-02-26 06:42:44
【问题描述】:
我在优化这个 PHP 函数的性能时遇到了麻烦,witch 应该返回请求的第一个 $n 个素数。该请求是通过表格提出的,当我请求前 10 000 个素数时,执行时间超过了 30 秒。时间限制并返回致命错误。如果您能给我一些关于如何使功能更好的提示,我将非常感激。
function fprimes($n){
//The Primes Array
$history = array(2,3);
//number to be tested
$item = 4;
//Set indicator for primacy
$build = 1;
if($n == 0){
echo "No primes requested!";
}
elseif($n == 1){
echo "The first prime number is: ".$n;
}
elseif($n == 2){
echo "The first ".$n." prime numbers are: </br> 1 </br> 2";
}
elseif($n > 2){
while((count($history)+1)<$n){
foreach($history as $prime){
if($item%$prime!=0){
$build++;
}
}
if((count($history)+1)==$build){
$history[]=$item;
}
$build = 1;
$item++;
}
echo "The first prime ".$n." numbers are: </br>1";
foreach($history as $printPrime){
echo "</br>".$printPrime;
}
}
}
【问题讨论】:
-
离题:1 不是素数。
-
I
m sorry, but its 就是我被教导的方式 :) 每次问题是否是质数时,老师都会陷入宗教辩论:)
标签: php performance function optimization