Permutation of first N positive integers such that prime numbers are at prime indices | Set 2 |  ; Computing count of prime numbers using sieve ; Computing permutations for primes ; Computing permutations for non - primes ; Driver program
var MOD = parseInt ( 1e9 + 7 ) ; function numPrimeArrangements ( n ) { var prime = Array . from ( { length : n + 1 } , ( _ , i ) => true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( var i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( prime [ i ] ) for ( factor = 2 ; factor * i <= n ; factor ++ ) prime [ factor * i ] = false ; } var primeIndices = 0 ; for ( var i = 1 ; i <= n ; i ++ ) if ( prime [ i ] ) primeIndices ++ ; var mod = parseInt ( ( 1e9 + 7 ) ) , res = 1 ; for ( var i = 1 ; i <= primeIndices ; i ++ ) res = ( ( 1 * res * i ) % mod ) ; for ( var i = 1 ; i <= ( n - primeIndices ) ; i ++ ) res = ( ( 1 * res * i ) % mod ) ; return res ; } var N = 5 ; document . write ( numPrimeArrangements ( N ) ) ;