-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPrimes.java
More file actions
54 lines (41 loc) · 867 Bytes
/
Primes.java
File metadata and controls
54 lines (41 loc) · 867 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
46
47
48
49
50
51
52
53
54
import java.util.Scanner;
class Primes{
public static void main(String[] args){
Primes exe = new Primes();
exe.begin();
}
void begin(){
Scanner l = new Scanner(System.in);
boolean[] isPrime;
int N;
N = l.nextInt();
isPrime = calcPrimes(N);
l.close();
}
void init(boolean[] isPrime, int N){
for(int i=0;i<N;i++)
isPrime[i] = true;
isPrime[0] = isPrime[1] = false;
}
boolean[] calcPrimes(int N){
int i,j,primeCounter = 0;
boolean[] isPrime = new boolean[N];
init(isPrime, N);
if(N>=2)
primeCounter = 1;
//The only even prime is 2
for(i=4;i<N;i+=2)
isPrime[i] = false;
//Be wary of overflow
for(i=3;i<N;i+=2){
if(isPrime[i]){
primeCounter++;
for(j=i*i;j<N;j+=i){
isPrime[j] = false;
}
}
}
System.out.println(primeCounter+" <= "+N);
return isPrime;
}
}