- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
45 lines (36 loc) · 850 Bytes
/
Copy pathMain.java
File metadata and controls
45 lines (36 loc) · 850 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
importjava.util.Arrays;
/*
@author: mc-es
Problem 10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Answer: 142913828922
*/
publicclassMain {
publicstaticvoidmain(String[] args) {
System.out.println(sumOfPrimes(2000000));
}
publicstaticlongsumOfPrimes(intn) {
boolean[] sieve = newboolean[n];
Arrays.fill(sieve, true);
sieve[0] = false; // 1 is not prime
inti = 2;
while (i * i <= n) {
if (sieve[i - 1]) {
// Mark all multiples of i as composite
for (intj = i * i; j <= n; j += i) {
sieve[j - 1] = false;
}
}
i++;
}
// Sum all primes
longtotal = 0;
for (intk = 1; k < n; k++) {
if (sieve[k]) {
total += k + 1; // Adjust for 0-based index
}
}
returntotal;
}
}