Project Euler #10:
The sum of the primes below 10 is \$2 + 3 + 5 + 7 = 17\$.
Find the sum of all the primes below two million.
My solution:
public class PrimeSumFinder {
private static final int MAX = 2_000_000;
public static void main(String[] args) {
long time = System.nanoTime();
long result = getSumOfPrimesBelowN(MAX);
time = System.nanoTime() - time;
System.out.println("Result: " + result
+ "\nTime used to calculate in nanoseconds: " + time);
}
private static long getSumOfPrimesBelowN(int n) {
boolean[] isPrimeArray = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
isPrimeArray[i] = true;
}
for (int i = 2; i * i <= n; i++) {
if (isPrimeArray[i]) {
for (int j = i; i * j <= n; j++) {
isPrimeArray[i * j] = false;
}
}
}
// Sum the primes
int index = 0;
long result = 0;
for(boolean isPrime : isPrimeArray) {
if(isPrime) {
result += index;
}
index++;
}
return result;
}
}
Output:
Result: 142913828922
Time used to calculate in nanoseconds: 87694113
Questions:
- Is this the most efficient way? If not, what is a better way?
- Does it have bad practices in it?