Created
July 30, 2012 05:10
-
-
Save zfogg/3204921 to your computer and use it in GitHub Desktop.
Recursive Prime Sieve Class
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
public class Primes { | |
public static void main(String[] args) { | |
//Print the primes up to 107. | |
for (Integer p : new RPrimeSieve(107)) | |
System.out.println(p); | |
} | |
} |
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
package primes; | |
import java.util.Iterator; | |
class RPrimeSieve implements Iterable<Integer> { | |
private Integer prime; | |
private Boolean[] sieve; | |
public RPrimeSieve(Integer max) { | |
this(2, initSieve(new Boolean[max+1])); | |
} | |
private RPrimeSieve(Integer p, Boolean[] sieve) { | |
this.sieve = sieve; | |
prime = nextPrime(p); | |
} | |
private static Boolean[] initSieve(Boolean[] sieve) { | |
for (Integer i = 2; i < sieve.length; i++) | |
sieve[i] = true; | |
return sieve; | |
} | |
private Integer nextPrime(Integer p) { | |
for (Integer i = p; i < sieve.length; i++) | |
if (sieve[i]) | |
return i; | |
return sieve.length+1; | |
} | |
private RPrimeSieve next() { | |
if (prime < sieve.length) { | |
markMultiples(prime); | |
return new RPrimeSieve(this.prime, sieve); | |
} | |
return null; | |
} | |
private void markMultiples(Integer n) { | |
for (Integer i = 1, j = n; j < sieve.length; i++, j = i*n) | |
sieve[j] = false; | |
} | |
public Iterator<Integer> iterator() { | |
final RPrimeSieve that = this; | |
return new Iterator<Integer>() { | |
private RPrimeSieve cur = that, | |
next; | |
public void remove() { throw new UnsupportedOperationException(); } | |
public boolean hasNext() { | |
next = cur.next(); | |
return next != null; | |
} | |
public Integer next() { | |
Integer r = cur.prime; | |
cur = next; | |
return r; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for writing this useful program.