0

我完全被困在这里。下面这个简单的代码刚刚停止工作。我调整了一些变量,现在它循环了一分钟,然后什么也没显示。问题应该出在方法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>
4

2 回答 2

1

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

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

于 2013-01-04T19:15:30.807 回答
0

Not sure if that would help, but class constants in PHP shall be accesses with the keyword self

$this::COLUMNS    ====> self::COLUMNS
$this::MAX_PRIMES ====> self::MAX_PRIMES
于 2013-01-04T19:30:27.563 回答