Find permutation of first N natural numbers that satisfies the given condition | Java implementation of the approach ; Function to find permutation ( p ) of first N natural numbers such that there are exactly K elements of permutation such that GCD ( p [ i ] , i ) > 1 ; First place all the numbers in their respective places ; Modify for first n - k integers ; In first index place n - k ; Print the permutation ; Driver code
class GFG { static void Permutation ( int n , int k ) { int [ ] p = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) p [ i ] = i ; for ( int i = 1 ; i < n - k ; i ++ ) p [ i + 1 ] = i ; p [ 1 ] = n - k ; for ( int i = 1 ; i <= n ; i ++ ) System . out . print ( p [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 5 , k = 2 ; Permutation ( n , k ) ; } }