-
Notifications
You must be signed in to change notification settings - Fork 3
/
count-primes.cpp
61 lines (45 loc) · 949 Bytes
/
count-primes.cpp
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
60
61
//Runtime: 289 ms
class Solution {
public:
bool isprime(int n)
{
if(n<=1) return 0;
if(n<=3) return 1;
if(n%2==0 || n%3==0) return 0;
int i =5;
while(i*i<=n)
{
if(n%i==0 || n%(i+2) == 0)
return 0;
i+=6;
}
return 1;
}
int countPrimes(int n) {
int cnt = 0;
for(int i=0;i<n;i++)
if(isprime(i))
cnt++;
return cnt;
}
};
//Runtime: 16 ms
//sieve of eratosthenes
class Solution {
public:
int countPrimes(int n) {
int cnt = 0;
if(n<=2)
return 0;
bool S[n+1];
memset(S, true, sizeof(S));
for(int i=2;i<sqrt(n);i++)
if(S[i])
for(int j=i*i;j<=n;j+=i)
S[j] = 0;
for(int i=2;i<n;i++)
if(S[i])
cnt++;
return cnt;
}
};