Permutation of first N positive integers such that prime numbers are at prime indices | Set 2 | Python3 program to count permutations from 1 to N such that prime numbers occur at prime indices ;  ; Computing count of prime numbers using sieve ; Computing permutations for primes ; Computing permutations for non - primes ; Driver code
import math ; NEW_LINE def numPrimeArrangements ( n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if prime [ i ] : NEW_LINE INDENT factor = 2 NEW_LINE while factor * i <= n : NEW_LINE INDENT prime [ factor * i ] = False NEW_LINE factor += 1 NEW_LINE DEDENT DEDENT DEDENT primeIndices = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if prime [ i ] : NEW_LINE INDENT primeIndices += 1 NEW_LINE DEDENT DEDENT mod = 1000000007 NEW_LINE res = 1 NEW_LINE for i in range ( 1 , primeIndices + 1 ) : NEW_LINE INDENT res = ( res * i ) % mod NEW_LINE DEDENT for i in range ( 1 , n - primeIndices + 1 ) : NEW_LINE INDENT res = ( res * i ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( numPrimeArrangements ( N ) ) NEW_LINE DEDENT