Created
August 23, 2011 21:57
-
-
Save dionyziz/1166705 to your computer and use it in GitHub Desktop.
An interesting way to implement the Sieve of Eratosthenes in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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