File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments