public class GroovyPrimes {
int cnt = 0
final def primes = []
final int size
public GroovyPrimes(int n){
size = n
init()
}
int last() {
primes[cnt-1]
}
private void init(){
int i = 2
int max = calcSize()
def nums = [true]*max
while (i < max && primes.size() < size) {
int p = i
if (nums[i]) {
primes << p
(p..(max/p)).each{ j-> if (p*j < max) nums[p*j] = false}
}
i += 1
}
}
private int calcSize(){
int max = 2
while ((max / Math.log(max)) < size &&
max < Integer.MAX_VALUE && max > 0) {
max *= 2
}
max
}
}
Tuesday, May 05, 2009
JavaOne Talk: Groovy Prime Sieve
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment