File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 289 ms
2
+ class Solution {
3
+ public:
4
+
5
+ bool isprime (int n)
6
+ {
7
+ if (n<=1 ) return 0 ;
8
+
9
+ if (n<=3 ) return 1 ;
10
+
11
+ if (n%2 ==0 || n%3 ==0 ) return 0 ;
12
+
13
+ int i =5 ;
14
+
15
+ while (i*i<=n)
16
+ {
17
+ if (n%i==0 || n%(i+2 ) == 0 )
18
+ return 0 ;
19
+
20
+ i+=6 ;
21
+ }
22
+ return 1 ;
23
+ }
24
+
25
+ int countPrimes (int n) {
26
+ int cnt = 0 ;
27
+
28
+ for (int i=0 ;i<n;i++)
29
+ if (isprime (i))
30
+ cnt++;
31
+
32
+ return cnt;
33
+ }
34
+ };
35
+
36
+ // Runtime: 16 ms
37
+ // sieve of eratosthenes
38
+ class Solution {
39
+ public:
40
+
41
+ int countPrimes (int n) {
42
+ int cnt = 0 ;
43
+
44
+ if (n<=2 )
45
+ return 0 ;
46
+
47
+ bool S[n+1 ];
48
+ memset (S, true , sizeof (S));
49
+
50
+ for (int i=2 ;i<sqrt (n);i++)
51
+ if (S[i])
52
+ for (int j=i*i;j<=n;j+=i)
53
+ S[j] = 0 ;
54
+
55
+ for (int i=2 ;i<n;i++)
56
+ if (S[i])
57
+ cnt++;
58
+
59
+ return cnt;
60
+ }
61
+ };
You can’t perform that action at this time.
0 commit comments