Generate all possible permutations of a Number divisible by N | Java program to implement the above approach ; Function to Swap two characters ; Function to generate all permutations and print the ones that are divisible by the N ; Convert String to integer ; Check for divisibility and print it ; Print all the permutations ; Swap characters ; Permute remaining characters ; Revoke the swaps ; Driver Code
class GFG { static void swap_ ( char [ ] a , int l , int i ) { char temp ; temp = a [ l ] ; a [ l ] = a [ i ] ; a [ i ] = temp ; } static void permute ( char [ ] str , int l , int r , int n ) { int i ; if ( l == r ) { int j = Integer . valueOf ( String . valueOf ( str ) ) ; if ( j % n == 0 ) System . out . print ( String . valueOf ( str ) + "NEW_LINE"); return ; } for ( i = l ; i < r ; i ++ ) { swap_ ( str , l , i ) ; permute ( str , l + 1 , r , n ) ; swap_ ( str , l , i ) ; } } public static void main ( String [ ] args ) { String str = "125" ; int n = 5 ; int len = str . length ( ) ; if ( len > 0 ) permute ( str . toCharArray ( ) , 0 , len , n ) ; } }