Tuesday, May 05, 2009

JavaOne Talk: Groovy Prime Sieve

See this post for an explanation on why this code is being shown and what kind of responses would be useful. See this post for the Java algorithm to compare against.

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
}
}

No comments: