Skip to content

Commit a4cc679

Browse files
authored
Create prime-arrangements.cpp
1 parent 2ffd350 commit a4cc679

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

C++/prime-arrangements.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int numPrimeArrangements(int n) {
7+
int cnt = count_primes(n);
8+
return static_cast<uint64_t>(factorial(cnt)) * factorial(n - cnt) % MOD;
9+
}
10+
11+
private:
12+
int count_primes(int n) {
13+
if (n <= 1) {
14+
return 0;
15+
}
16+
vector<bool> is_primes((n + 1) / 2, true);
17+
int cnt = is_primes.size();
18+
for (int i = 3; i * i <= n; i += 2) {
19+
if (!is_primes[i / 2]) {
20+
continue;
21+
}
22+
for (int j = i * i; j <= n; j += 2 * i) {
23+
if (!is_primes[j / 2]) {
24+
continue;
25+
}
26+
--cnt;
27+
is_primes[j / 2] = false;
28+
}
29+
}
30+
return cnt;
31+
}
32+
33+
int factorial(int n) {
34+
int result = 1ull;
35+
for (int i = 2; i <= n; ++i) {
36+
result = (static_cast<uint64_t>(result) * i) % MOD;
37+
}
38+
return result;
39+
}
40+
41+
static const int MOD = 1e9 + 7;
42+
};

0 commit comments

Comments
 (0)