We have to find the number of permutations of 1 to n, so the prime numbers are placed at prime indices. The answers may be large, return the answer modulo 10^9 + 7. So if n = 5, then output will be 12. So there will be 12 permutations. one possible permutation will be [1,2,5,4,3], one invalid permutation is [5,2,3,4,1] because 5 is placed at index 1, that is not prime.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def getNum(self,n): primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] i = 0 while i < len(primes): if primes[i]>n: return i i+=1 return len(primes) def numPrimeArrangements(self, n): """ :type n: int :rtype: int """ x = self.getNum(n) p = 1 m = 1000000000+7 for i in range(x,0,-1): p*=i p%=m for i in range(n-x,0,-1): p*=i p%=m return p