-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountPrimes.java
More file actions
32 lines (32 loc) · 814 Bytes
/
CountPrimes.java
File metadata and controls
32 lines (32 loc) · 814 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
import java.util.*;
public class CountPrimes {
private static int sieve(int n){
if (n == 0) {
return 0;
}
boolean[] p = new boolean[n+1];
Arrays.fill(p, true);
p[0]=p[1]=false;
for (int i = 2; i*i <= n; i++) {
if (p[i] == true) {
for (int j = i*i; j <= n; j += i) {
p[j] = false;
}
}
}
int count = 0;
for (int i = 1; i <= n; i++) {
if (p[i] == true) {
count++;
}
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ans = sieve(n);
System.out.println(ans);
sc.close();
}
}