0

私はここで完全に立ち往生しています。以下のこの単純なコードは、機能を停止しました。いくつかの変数を調整しましたが、1分ほどループしてから、何も表示されません。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>
4

2 に答える 2

1

$currentNumber++if句の外側に移動します。

コードが非素数に達すると、その数で停止し、インクリメントを継続しません$currentNumber

于 2013-01-04T19:15:30.807 に答える
0

それが役立つかどうかはわかりませんが、PHPのクラス定数はキーワードを使用してアクセスする必要がありますself

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