【问题标题】:Can someone help me optimize this "request prime numbers" PHP Function有人可以帮我优化这个“请求素数”PHP函数吗
【发布时间】: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 不是素数。
  • Im sorry, but its 就是我被教导的方式 :) 每次问题是否是质数时,老师都会陷入宗教辩论:)

标签: php performance function optimization


【解决方案1】:

我看到的一个超级简单的优化是你可以这样做:

$item += 2;

因为偶数绝不是素数(2 除外)。


一项与素数无关的优化是跟踪您找到的素数的数量,而不是每次都重新评估count($history)

【讨论】:

  • count 不应该比读取变量慢,它只是数组中的一个标题字段,它实际上不必线性计数。
  • 另一个优化是在大于sqrt($item)时停止检查历史记录。
  • 有时显而易见的东西是最难看到的 :) 谢谢 :)
  • 您也可以在$item % prime == 0 时添加breakif($item%$prime!=0){$build++;} else {break;} - 如果它分开,肯定不会是素数。
  • 是的,我很确定 foreach 不好,因为您只需要找到 one 反例。我假设代码做到了,但我想它没有。好眼力。这也解释了为什么+= 2 对性能有巨大的影响。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多