-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountPrimes.java
More file actions
44 lines (37 loc) · 1.15 KB
/
CountPrimes.java
File metadata and controls
44 lines (37 loc) · 1.15 KB
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
package data_structures;
public class CountPrimes {
/**
* Given an integer n, return the number of prime numbers that are strictly less than n.
* @param n
* @return number of prime numbers
*/
public static int countPrimes(int n) {
// base case, list [0, 1] no primes
if (n <= 2) return 0;
int count = 0;
// sentinel values to distinguish prime nums
// true: non-prime, false: prime
boolean[] sentinels = new boolean[n];
for (int num = 2; num <= (int)Math.sqrt(n); num++) {
if (sentinels[num] == false) {
for (int j = num*num; j < n; j += num ) {
sentinels[j] = true;
}
}
}
// count primes
for (int i = 2; i < n; i++) {
if (sentinels[i] == false) {
System.out.print(i + " ");
count++;
}
}
System.out.println();
return count;
}
public static void main(String[] args) {
int n = 20;
int count = countPrimes(n);
System.out.println("n = " + n + ", count = " + count);
}
}