Skip to content

Commit d5f5f97

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <[email protected]>
1 parent 668052e commit d5f5f97

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

0204_count_primes/count_primes.c

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33
#include <stdbool.h>
4-
#include <string.h>
54

6-
static int countPrimes(int n)
5+
6+
int countPrimes(int n)
77
{
8-
if (n < 3) return 0;
9-
8+
if (n < 3) {
9+
return 0;
10+
}
11+
1012
int i, j;
1113
bool *marked = malloc(n);
1214
memset(marked, false, n);

0204_count_primes/count_primes.cc

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#include <stdc++.h>
2+
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
int countPrimes(int n) {
8+
if (n < 3) {
9+
return 0;
10+
}
11+
12+
vector<bool> marked(n);
13+
int count = n >> 1;
14+
for (int i = 3; i * i <= n; i += 2) {
15+
if (!marked[i]) {
16+
for (int j = i * i; j < n; j += (i << 1)) {
17+
if (!marked[j]) {
18+
marked[j] = true;
19+
--count;
20+
}
21+
}
22+
}
23+
}
24+
return count;
25+
}
26+
};

0 commit comments

Comments
 (0)