Skip to content

Instantly share code, notes, and snippets.

@dionyziz
Created August 23, 2011 21:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dionyziz/1166705 to your computer and use it in GitHub Desktop.
Save dionyziz/1166705 to your computer and use it in GitHub Desktop.
An interesting way to implement the Sieve of Eratosthenes in PHP
<?php
class PrimeIterator implements Iterator {
private $i;
private $primes;
private function generateNextPrime() {
$candidate = $this->primes[ count( $this->primes ) - 1 ];
do {
$candidate += 2;
$isPrime = true;
foreach ( $this->primes as $prime ) {
if ( $candidate % $prime == 0 ) {
$isPrime = false;
break;
}
if ( $prime * $prime > $candidate ) {
break;
}
}
} while ( !$isPrime );
$this->primes[] = $candidate;
}
public function __construct() {
$this->primes = array( 2, 3 );
$this->rewind();
}
public function rewind() {
$this->i = 0;
}
public function current() {
if ( !isset( $this->primes[ $this->i ] ) ) {
$this->generateNextPrime();
}
return $this->primes[ $this->i ];
}
public function key() {
return $this->i;
}
public function next() {
++$this->i;
}
public function valid() {
return true;
}
}
$primes = new PrimeIterator();
$i = 0;
foreach ( $primes as $prime ) {
echo $prime . "\n";
if ( $i > 10 ) {
break;
}
++$i;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment