Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 素数循环的永久搜索方法_Php_Primes - Fatal编程技术网

Php 素数循环的永久搜索方法

Php 素数循环的永久搜索方法,php,primes,Php,Primes,我完全被困在这里了。下面这个简单的代码刚刚停止工作。我调整了一些变量,现在它循环了一分钟,然后什么也没显示。 问题应该在方法isPrime或collectPrimes中。有什么想法吗?提前谢谢 <?php class PrimeNumbers { const COLUMNS = 5; const MAX_PRIMES = 100; public $primes = array(); public function isPrime($z) {

我完全被困在这里了。下面这个简单的代码刚刚停止工作。我调整了一些变量,现在它循环了一分钟,然后什么也没显示。 问题应该在方法
isPrime
collectPrimes
中。有什么想法吗?提前谢谢

<?php

class PrimeNumbers
{
    const COLUMNS = 5;
    const MAX_PRIMES = 100;
    public $primes = array();

    public function isPrime($z) {
        for ($i = 2; $i < $z; $i++)
        {
            if (($z % $i) == 0) {
                return false;
            }   
        }
        return true;
    }

    public function collectPrimes() {
        $currentNumber = 1;
        while (count($this->primes) <= $this::MAX_PRIMES) {
            if ($this->isPrime($currentNumber)) {
                array_push($this->primes, $currentNumber);
                $currentNumber++;
            }
        }
    }

    public function outputGrid() {
        $columnCounter = 0;
        $output = "";

        $output .= "<table>";

        foreach ($this->primes as $prime) {
            if ($columnCounter == 0) {
               $output .= "<tr>";
            } else if ($columnCounter == $this::COLUMNS) {
                $output .= "</tr>";
                $columnCounter = 0;
            }
            $columnCounter++;
            $output .= "<td>".$prime."</td>";
        }

        $output .= "</table>";
        return $output;
    }
}

?>
<html>
<head><title>1000 Primzahlen</title></head>
<body>


<?php 

  $pr = new PrimeNumbers();
  $pr->collectPrimes();
  echo $pr->outputGrid();
  var_dump($pr->primes);

?>

</body>
</html>

1000普里姆扎伦

将$currentNumber++移到if子句之外


每当代码达到非素数时,它将停止在该数字处,并且不会继续递增
$currentNumber

不确定这是否有帮助,但PHP中的类常量应使用关键字
self
进行访问

$this::COLUMNS    ====> self::COLUMNS
$this::MAX_PRIMES ====> self::MAX_PRIMES

您是否尝试过增加
max_execution_time
以查看是否需要更长的时间?您是否尝试过调试它?顺便说一句,您的算法效率极低。您正在使用一种非常低效的方法来计算素数-很可能,这只需要花费大量时间。在ErastothenesI的筛子上仔细阅读我认为
$currentNumber++
放错地方了(你找到的第一个非素数会使循环卡住)…但是正如最初的评论所说,你的代码效率极低。看一看Erastothene筛