Project-Euler / 10
Problem 10 asks:
Find the sum of all the primes below two million.
Here’s my solution in Java:
public class Problem10 { public static void main(String[] args) { int max = 2_000_000; boolean[] isComposite = new boolean[max + 1]; for (int i = 2; i * i <= max; i++) { if (!isComposite[i]) { for (int j = i; i * j <= max; j++) isComposite[i*j] = true; } } long sum = 0; for (int i = 2; i <= max; i++) if (!isComposite[i]) sum += i; System.out.println(sum); } }
It uses the sieve of Eratosthenes algorithm. It could be optimized by using the sieve of Atkin, and/or using a bit vector instead of a boolean array, but as is it runs in a very fast time.