Skip to content

Instantly share code, notes, and snippets.

@tec27
Created July 14, 2012 06:56
Show Gist options
  • Save tec27/3109772 to your computer and use it in GitHub Desktop.
Save tec27/3109772 to your computer and use it in GitHub Desktop.
Euler 10
import java.util.BitSet;
public class Euler10 {
private static BitSet runSieve(int limit) {
BitSet bits = new BitSet(limit+1);
int sievingLimit = (int)Math.ceil(Math.sqrt(limit));
for(int n = 2; n <= limit; n = bits.nextClearBit(n+1)) {
if(n > sievingLimit) break; // any composites will be past the limit
for(int m = n*n; m > n && m <= limit; m += n) {
bits.set(m, true);
}
}
return bits;
}
/**
* @param args
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();
int limit = 2000000;
BitSet sieve = runSieve(limit);
long sum = 0;
for(int n = 2; n < limit; n = sieve.nextClearBit(n+1)) {
sum += n;
}
System.out.println("Took " + (System.currentTimeMillis() - start) + "ms");
System.out.println("Result: " + sum);
}
}
Took 27ms
Result: 142913828922
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment