Return the number of permutations of 1 to n
so that prime numbers are at prime indices (1-indexed.)
(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)
Since the answer may be large, return the answer modulo 10^9 + 7
.
Example 1:
Input: n = 5 Output: 12 Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
Example 2:
Input: n = 100 Output: 682289015
Constraints:
1 <= n <= 100
Solution: Permutation
Count the number of primes in range [1, n], assuming there are p primes and n – p non-primes, we can permute each group separately.
ans = p! * (n – p)!
Time complexity: O(nsqrt(n))
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Author: Huahua class Solution { public: int numPrimeArrangements(int n) { const int kMod = 1e9 + 7; int p = 0; for (int i = 1; i <= n; ++i) p += isPrime(i); long ans = 1; for (int i = 1; i <= p; ++i) ans = (ans * i) % kMod; for (int i = 1; i <= n - p; ++i) ans = (ans * i) % kMod; return ans; } private: bool isPrime(int x) { if (x < 2) return false; if (x == 2) return true; for (int i = 2; i <= sqrt(x); ++i) if (x % i == 0) return false; return true; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment