Open In App

Generate all possible permutations of a Number divisible by N

Last Updated : 12 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a numerical string S, the task is to print all the permutations of the string which are divisible by N.

Examples:

Input: N = 5, S = “125” 
Output: 125 215
Explanation: 
All possible permutations are S are {125, 152, 215, 251, 521, 512}. 
Out of these 6 permutations, only 2 {125, 215} are divisible by N (= 5).

Input: N = 7, S = “4321” 
Output: 4312 4123 3241

Approach: The idea is to generate all possible permutations and for each permutation, check if it is divisible by N or not. For each permutation found to be divisible by N, print them.

Below is the implementation of the above approach:

C++14




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to Swap two
// characters
void swap_(char& a, char& b)
{
    char temp;
    temp = a;
    a = b;
    b = temp;
}
 
// Function to generate all permutations
// and print the ones that are
// divisible by the N
void permute(char* str, int l, int r, int n)
{
    int i;
 
    if (l == r) {
 
        // Convert string to integer
        int j = atoi(str);
 
        // Check for divisibility
        // and print it
        if (j % n == 0)
            cout << str << endl;
 
        return;
    }
 
    // Print all the permutations
    for (i = l; i < r; i++) {
 
        // Swap characters
        swap_(str[l], str[i]);
 
        // Permute remaining
        // characters
        permute(str, l + 1, r, n);
 
        // Revoke the swaps
        swap_(str[l], str[i]);
    }
}
 
// Driver Code
int main()
{
    char str[100] = "125";
    int n = 5;
    int len = strlen(str);
 
    if (len > 0)
        permute(str, 0, len, n);
 
    return 0;
}


Java




// Java program to implement
// the above approach
class GFG{
 
// Function to Swap two
// characters
static void swap_(char []a, int l, int i)
{
    char temp;
    temp = a[l];
    a[l] = a[i];
    a[i] = temp;
}
 
// Function to generate all permutations
// and print the ones that are
// divisible by the N
static void permute(char[] str, int l,
                         int r, int n)
{
    int i;
 
    if (l == r)
    {
         
        // Convert String to integer
        int j = Integer.valueOf(String.valueOf(str));
 
        // Check for divisibility
        // and print it
        if (j % n == 0)
            System.out.print(String.valueOf(str) + "\n");
 
        return;
    }
 
    // Print all the permutations
    for(i = l; i < r; i++)
    {
         
        // Swap characters
        swap_(str, l, i);
 
        // Permute remaining
        // characters
        permute(str, l + 1, r, n);
 
        // Revoke the swaps
        swap_(str, l, i);
    }
}
 
// Driver Code
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);
}
}
 
// This code is contributed by amal kumar choubey


Python3




# Python3 Program to implement
# the above approach
 
# Function to generate all
# permutations and print
# the ones that are
# divisible by the N
def permute(st, l, r, n):
 
    if (l == r):
 
        # Convert string
        # to integer
        p = ''.join(st)
        j = int(p)
 
        # Check for divisibility
        # and print it
        if (j % n == 0):
            print (p)
 
        return
 
    # Print all the
    # permutations
    for i in range(l, r):
 
        # Swap characters
        st[l], st[i] = st[i], st[l]
 
        # Permute remaining
        # characters
        permute(st, l + 1, r, n)
 
        # Revoke the swaps
        st[l], st[i] = st[i] ,st[l]
 
# Driver Code
if __name__ == "__main__":
 
    st = "125"
    n = 5
    length = len(st)
 
    if (length > 0):
      p = list(st)
      permute(p, 0, length, n);
 
# This code is contributed by rutvik_56


C#




// C# program to implement
// the above approach
using System;
 
class GFG{
  
// Function to Swap two
// characters
static void swap_(char []a, int l,
                            int i)
{
    char temp;
    temp = a[l];
    a[l] = a[i];
    a[i] = temp;
}
  
// Function to generate all permutations
// and print the ones that are
// divisible by the N
static void permute(char[] str, int l,
                         int r, int n)
{
    int i;
  
    if (l == r)
    {
         
        // Convert String to integer
        int j = Int32.Parse(new string(str));
  
        // Check for divisibility
        // and print it
        if (j % n == 0)
            Console.Write(new string(str) + "\n");
  
        return;
    }
  
    // Print all the permutations
    for(i = l; i < r; i++)
    {
         
        // Swap characters
        swap_(str, l, i);
  
        // Permute remaining
        // characters
        permute(str, l + 1, r, n);
  
        // Revoke the swaps
        swap_(str, l, i);
    }
}
  
// Driver Code
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);
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to Swap two
// characters
function swap_(a, l, i)
{
    let temp;
    temp = a[l];
    a[l] = a[i];
    a[i] = temp;
}
 
// Function to generate all permutations
// and print the ones that are
// divisible by the N
function permute(str, l, r, n)
{
    let i;
  
    if (l == r)
    {
         
        // Convert String to integer
        let j = parseInt((str).join(""));
  
        // Check for divisibility
        // and print it
        if (j % n == 0)
            document.write((str).join("") + "<br>");
  
        return;
    }
  
    // Print all the permutations
    for(i = l; i < r; i++)
    {
         
        // Swap characters
        swap_(str, l, i);
  
        // Permute remaining
        // characters
        permute(str, l + 1, r, n);
  
        // Revoke the swaps
        swap_(str, l, i);
    }
}
 
// Driver Code
let str = "125";
let n = 5;
let len = str.length;
 
if (len > 0)
    permute(str.split(""), 0, len, n);
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output: 

125
215

 

Time Complexity: O(N!)
Auxiliary Space: O(N)



Similar Reads

Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Generate all possible permutations of words in a Sentence
Given a string S, the task is to print permutations of all words in a sentence. Examples: Input: S = “sky is blue”Output: sky is bluesky blue isis sky blueis blue skyblue sky isblue is sky Input: S =” Do what you love”Output:Do what you loveDo what love youDo you what loveDo you love whatDo love what youDo love you whatwhat Do you lovewhat Do love
13 min read
Generate all cyclic permutations of a number
Given a number N, our task is to generate all the possible cyclic permutations of the number. A cyclic permutation shifts all the elements of a set by a fixed offset. For a set with elements [Tex]a_0 [/Tex], [Tex]a_1 [/Tex], ..., [Tex]a_n [/Tex], a cyclic permutation of one place to the left would yield [Tex]a_1 [/Tex], ..., [Tex]a_n [/Tex], [Tex]a
6 min read
Smallest number containing all possible N length permutations using digits 0 to D
Given two integer N and D, the task is to find the size of the smallest string that contains all permutations of length N that can be formed using first D digits (0, 1, ..., D-1).Examples: Input: N = 2, D = 2 Output: 01100 Explanation: Possible permutations of length 2 from digits (0, 1) are {00, 01, 10, 11}. "01100" is one such string that contain
7 min read
Generate all permutations of a string that follow given constraints
Given a string, generate all permutations of it that do not contain 'B' after 'A', i.e., the string should not contain "AB" as a substring. Examples: Input : str = "ABC" Output : ACB, BAC, BCA, CBA Out of 6 permutations of "ABC", 4 follow the given constraint and 2 ("ABC" and "CAB") do not follow. Input : str = "BCD" Output : BCD, BDC, CDB, CBD, DC
11 min read
Generate longest possible array with product K such that each array element is divisible by its previous adjacent element
Given an integer K, the task is to construct an array of maximum length with product of all array elements equal to K, such that each array element except the first one is divisible by its previous adjacent element.Note: Every array element in the generated array must be greater than 1. Examples: Input: K = 4Output: {2, 2}Explanation:The second ele
7 min read
Number of possible permutations when absolute difference between number of elements to the right and left are given
Given an array of N elements where each element i, the absolute difference between total elements to the right and left of it are given. Find the number of possible ordering of the actual array elements.Examples: Input : N = 5, arr[] = {2, 4, 4, 0, 2} Output : 4 There are four possible orders, as follows: 2, 1, 4, 5, 3 2, 5, 4, 1, 3 3, 1, 4, 5, 2 3
10 min read
Count all possible N-length vowel permutations that can be generated based on the given conditions
Given an integer N, the task is to count the number of N-length strings consisting of lowercase vowels that can be generated based the following conditions: Each 'a' may only be followed by an 'e'.Each 'e' may only be followed by an 'a' or an 'i'.Each 'i' may not be followed by another 'i'.Each 'o' may only be followed by an 'i' or a 'u'.Each 'u' m
12 min read
Count of possible permutations of a number represented as a sum of 2's, 4's and 6's only
Given an integer N, the task is to find out the number of permutations in which N can be represented as a sum of 2s, 4s, and 6s only.Note: The different permutations of the same combination will also be counted.Examples: Input: N = 8 Output: 7 Explanation: The possible combinations are: 2 2 2 2 4 4 4 2 2 2 2 4 2 4 2 2 6 6 2 Input: N = 6 Output: 4 A
9 min read
Generate a permutation of [0, N-1] with maximum adjacent XOR which is minimum among other permutations
Given an integer N, the task is to print a permutation of numbers from 0 to N-1, such that: There is no duplicate element in the permutationThe maximum adjacent XOR of this permutation is minimum among other permutationsThere can be more than one permutation present that satisfies these conditions. Examples: Input: N = 5Output: 1 2 3 0 4Explanation
6 min read