-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEuler10.java
53 lines (46 loc) · 1.04 KB
/
Euler10.java
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
46
47
48
49
50
51
52
53
public class Euler10 {
public static boolean isPrime(long i){
if(i != 2 && i % 2 == 0) return false; // even is not prime except 2
for(int x = 3; x <= Math.sqrt(i); x+=2){
if(i % x == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 2000000;
long sum = 0;
for(int i = 2; i < n; i++){
if(isPrime(i)){
sum+=i;
}
}
System.out.println(sum);
long nSum = 0;
boolean [] isPrime = new boolean[(n + 1)];
for(int i = 2; i < n; i++){
// Assume every number is prime except even numbers
if(i % 2 == 0 && i != 2){
isPrime[i] = false;
}else{
isPrime[i] = true;
}
}
for(int i = 3; i <= Math.sqrt(n); i+=2){ //only check for odd, cos we set odds to prime
if(isPrime[i]) {
for(int j = i*i; j < n; j+=i){ // mark all multiples of odd to false
isPrime[j] = false;
}
}
}
for(int i = 2; i < n; i++){
if(isPrime[i]){
//System.out.println(i);
nSum+= i;
}
}
System.out.println(nSum);
}
}