-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathcount_primes.java
59 lines (45 loc) · 1.36 KB
/
count_primes.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
54
55
56
57
58
59
/* Implement countPrimes(n), which calculates the number of primes that are strictly smaller than n.
Example 1:
Input: n=0
Output: 0
Example 2:
Input: n=10
Output: 4
Example 3:
Input: n=155
Output: 36
Example 4:
Input: n=5000000
Ouput: 348513
Constraints:
0 <= n <= 5 * 10^6
Time complexity: O(n^2)
Space complexity: O(n)
*/
class Solution {
int countPrimes(int n) {
if (n<=2) {
return 0;
}
int counter = 0;
/* notPrimesArray: Array in which every cell represents whether
its index number is non-prime or not. Initially every number is
considered prime (default value: false), but the opposite might be
determined later. */
boolean[] notPrimesArray = new boolean[n];
for (int i=2; i<n; i++) {
/* Any product of i>=2 multiplied by any integer j>=2 is not prime.
So the corresponding value of i*j in the array is changed to true.
This will only affect cells with an index number higher than the
current i, as i*j>i for any j>=2.*/
for (int j=2; i*j<n; j++) {
notPrimesArray[i*j] = true;
}
/* If a number is non-prime, the counter is updated. */
if (notPrimesArray[i]==false) {
counter++;
}
}
return counter;
}
};