Permutation of first N positive integers such that prime numbers are at prime indices | Set 2 | Java 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 program
import java . util . * ; class GFG { static int MOD = ( int ) ( 1e9 + 7 ) ; static int numPrimeArrangements ( int n ) { boolean [ ] prime = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( prime [ i ] ) for ( int factor = 2 ; factor * i <= n ; factor ++ ) prime [ factor * i ] = false ; } int primeIndices = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( prime [ i ] ) primeIndices ++ ; int mod = ( int ) ( 1e9 + 7 ) , res = 1 ; for ( int i = 1 ; i <= primeIndices ; i ++ ) res = ( int ) ( ( 1L * res * i ) % mod ) ; for ( int i = 1 ; i <= ( n - primeIndices ) ; i ++ ) res = ( int ) ( ( 1L * res * i ) % mod ) ; return res ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . print ( numPrimeArrangements ( N ) ) ; } }