Given an integer n
(1 <= n <= 100), you need to return the number of prime arrangements. The number prime arrangements is the number of permutations of the first n
positive integers such that prime numbers are at prime indices (1-indexed).
Return the number of prime arrangements modulo 10^9 + 7
.
n
is 1, what should the function return?
n
are prime.num_primes
prime numbers and (n - num_primes)
non-prime numbers:
num_primes
since those can be arranged amongst themselves.(n - num_primes)
for the non-prime numbers.10^9 + 7
.from math import factorial
MOD = 10**9 + 7
def numPrimeArrangements(n: int) -> int:
def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
num_primes = sum(1 for i in range(1, n + 1) if is_prime(i))
non_primes = n - num_primes
return (factorial(num_primes) * factorial(non_primes)) % MOD
# Example usage:
print(numPrimeArrangements(5)) # output should be 12
i
in the range from 1 to n
, we are potentially performing a check for primes that takes O(sqrt(n)).Given the constraints, this approach will be efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?