Prime Arrangements Problem
Description
LeetCode Problem 1175.
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
Approach: Count the Primes, Multiply Two Factorials
Say there are p primes in [1, n]. Then there are also exactly p prime indices, and the rule forces the p prime numbers onto them. Nothing else matters: the primes can fill the prime indices in any of p! orders, and the other n - p numbers (1 and the composites) fill the remaining indices in any of (n - p)! orders. The two choices are independent, so the answer is p! * (n - p)!.
To count the primes, use the Sieve of Eratosthenes: walk i from 2 to n; if i is not crossed out it is prime, so count it and cross out its multiples i*i, i*i + i, ....
Then build both factorials, taking the remainder modulo 109 + 7 after every multiplication so the numbers stay small. Note that 1 is not prime, so n = 1 gives 0! * 1! = 1.
Complexity: O(n log log n) time for the sieve plus O(n) for the factorials, and O(n) space.
class Solution:
def numPrimeArrangements(self, n: int) -> int:
MOD = 10**9 + 7
# Sieve of Eratosthenes: count the primes in [1, n].
is_prime = [True] * (n + 1)
primes = 0
for i in range(2, n + 1):
if is_prime[i]:
primes += 1
for j in range(i * i, n + 1, i):
is_prime[j] = False
# Primes go to the prime positions in any order, the rest to the others.
ans = 1
for i in range(2, primes + 1):
ans = ans * i % MOD
for i in range(2, n - primes + 1):
ans = ans * i % MOD
return ans