Prime Arrangements in Python


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 −

  • Define one method called getNum, as follows −
  • prime := list of all primes from 2 to 100
  • set i := 0
  • while i < length of prime list
    • if prime[i] > n, then return i
    • i := i + 1
  • return length of prime
  • The actual problem will be solved as follows
  • x := getNum(n), p := 1, m := 10^9 + 7
  • for i := x down to 0
    • p := p * i
    • p := p mod m
  • for i := n – x down to 0
    • p := p * i
    • p := p mod m
  • return p

Example

Let us see the following implementation to get better understanding −

 Live Demo

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
ob1 = Solution()
print(ob1.numPrimeArrangements(100))

Input

100

Output

682289015

Updated on: 29-Apr-2020

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements