forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountPrimes.java
39 lines (36 loc) · 1002 Bytes
/
CountPrimes.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
class Solution {
// TC : O(nloglogn)
// SC : O(n)
public int countPrimes(int n) {
boolean[] noList = new boolean[n];
int count = 0;
for(int i=2;i<n;i++){
if(noList[i] == false){ // i no is prime
count++;
for(int j=2;j*i<n;j++){
noList[i*j] = true; // i*j is marked non prime
}
}
}
return count;
}
}
// Solution 2 where inner loop is not starting from 2
class Solution {
// TC : O(nloglogn)
// SC : O(n)
public int countPrimes(int n) {
boolean[] noList = new boolean[n];
int count = 0;
for(int i=2;i<n;i++){
if(noList[i] == false){ // i no is prime
count++;
for(int factor=i;factor<n;){
noList[factor] = true; // factor is marked non prime
factor = factor + i;
}
}
}
return count;
}
}