Generate all possible permutations of a Number divisible by N | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap_ ( char & a , char & b ) { char temp ; temp = a ; a = b ; b = temp ; } void permute ( char * str , int l , int r , int n ) { int i ; if ( l == r ) { int j = atoi ( str ) ; if ( j % n == 0 ) cout << str << endl ; return ; } for ( i = l ; i < r ; i ++ ) { swap_ ( str [ l ] , str [ i ] ) ; permute ( str , l + 1 , r , n ) ; swap_ ( str [ l ] , str [ i ] ) ; } } int main ( ) { char str [ 100 ] = "125" ; int n = 5 ; int len = strlen ( str ) ; if ( len > 0 ) permute ( str , 0 , len , n ) ; return 0 ; }