Created
July 14, 2012 06:56
-
-
Save tec27/3109772 to your computer and use it in GitHub Desktop.
Euler 10
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
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); | |
} | |
} |
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
Took 27ms | |
Result: 142913828922 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment