永远搜索素数循环的方法

时间:2013-01-04 19:08:56

标签: php primes

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

<?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>

2 个答案:

答案 0 :(得分:1)

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

每当你的代码到达非素数时,它就会停在该数字处,并且不会继续增加$currentNumber

答案 1 :(得分:0)

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

进行访问
$this::COLUMNS    ====> self::COLUMNS
$this::MAX_PRIMES ====> self::MAX_PRIMES