Skip to content
Related Articles

Related Articles

Improve Article

Count all prime numbers that can be formed using digits of a given number

  • Difficulty Level : Hard
  • Last Updated : 11 Oct, 2021
Geek Week

Given a string S consisting of N digits, the task is to find the number of distinct Prime Numbers that can be formed using the digits of the string S.

Examples:

Input: S = “123”
Output: 5
Explanation:
The prime numbers that can be formed from the digits of the string S is 2, 3, 13, 23, and 31. Hence, the total count is 5.

Input: S = “1”
Output: 0

Approach: The given problem can be solved by using Depth First Search and Backtracking to find all possible permutations and check if they can be formed prime numbers or not. Follow the steps below to solve the problem:



  • Initialize a HashSet H to store the unique prime number strings possible.
  • Define a function check(string number) to check if the number is prime or not and perform the following steps:
    • If the length of the string number[] is 0, then, return false.
    • Use the function trim to trim the number.
    • Initialize a long variable num and store the parsed number in it using the parseLong function.
    • If num is equal to 1, then return false.
    • If num%2 is equal to 0 and num is not equal to 2, then, return false.
    • If num%3 is equal to 0 and num is not equal to 3, then, return false.
    • Iterate over a range [6, num1/2] using the variable i and perform the following steps:
      • If either of num%(i-1) or num%(i+1) is equal to 0, then, return false.
    • In the end, return true.
  • Define a function DFS(int arr[], string ans) to find all possible prime numbers and perform the following steps:
    • Call the function check(ans) and if the function returns true, then, add this string ans to the HashSet H.
    • Iterate over a range [0, 10] using the variable i and perform the following steps:
      • If arr[i] is equal to 0, then, continue the iteration.
      • Add the value of i to the string answer and decrease the value of arr[i] by 1.
      • Call the function DFS(arr, ans) to find other possible answers backtracking.
      • Remove the value of i from the string answer and add the value of arr[i] by 1.
  • Initialize an array count[] of size 10 to store the frequency of each number in the string S.
  • Iterate over a range [0, N] using the variable i and perform the following steps:
    • Add the frequency by 1 to the array count[] of the character in the ith index in the string S.
  • Call the function DFS(count, “”) to find all possible prime numbers.
  • After performing the above steps, print the size of the HashSet H as the answer.

Below is the implementation of the above approach.

C++




#include <bits/stdc++.h>
using namespace std;
unordered_set<string> H;
 
// Function to check whether the
// number is prime or not
bool check(string number)
{
    if (number.length() == 0) {
        return false;
    }
    long num = stol(number);
 
    // Condition for prime number
    if (num == 1) {
        return false;
    }
    if (num % 2 == 0 && num != 2) {
        return false;
    }
    if (num % 3 == 0 && num != 3) {
        return false;
    }
 
    // Iterate over the range [6, num]
    for (int i = 6; i * i <= num; i += 6) {
        if (num % (i - 1) == 0 || num % (i + 1) == 0) {
            return false;
        }
    }
 
    // Otherwisem return true
    return true;
}
 
// Function to count the total number
// of prime numbers
void DFS(int arr[], string ans)
{
    // Add it in the HashSet
    if (check(ans)) {
        H.insert(ans);
    }
 
    for (int i = 0; i <= 9; ++i) {
        if (arr[i] == 0) {
            continue;
        }
 
        // Use the number
        ans = (ans + to_string(i));
 
        // Decrease the number
        arr[i]--;
 
        // Perform the DFS Call
        DFS(arr, ans);
        ans = ans.substr(0, ans.length() - 1);
 
        // Backtracking the frequency
        arr[i]++;
    }
}
 
// Driver Code
int main()
{
    string number = "123";
    int count[10];
    for (int i = 0; i < 10; i++) {
        count[i] = 0;
    }
    for (int i = 0; i < number.length(); i++) {
        count[number[i] - '0']++;
    }
    H.clear();
    DFS(count, "");
    cout << H.size();
    return 0;
}
 
// This code is contributed by maddler.

Java




// Java program for the above approach
import java.util.*;
 
public class GFG {
    static HashSet<String> H = new HashSet<>();
 
    // Function to check whether the
    // number is prime or not
    static boolean check(String number)
    {
        if (number.length() == 0) {
            return false;
        }
        number = number.trim();
        long num = Long.parseLong(number);
 
        // Condition for prime number
        if (num == 1) {
            return false;
        }
        if (num % 2 == 0 && num != 2) {
            return false;
        }
        if (num % 3 == 0 && num != 3) {
            return false;
        }
 
        // Iterate over the range [6, num]
        for (int i = 6; i * i <= num; i += 6) {
            if (num % (i - 1) == 0 || num % (i + 1) == 0) {
                return false;
            }
        }
 
        // Otherwisem return true
        return true;
    }
 
    // Function to count the total number
    // of prime numbers
    static void DFS(int arr[], String ans)
    {
        // Add it in the HashSet
        if (check(ans) == true) {
            H.add(ans);
        }
 
        for (int i = 0; i <= 9; ++i) {
            if (arr[i] == 0) {
                continue;
            }
 
            // Use the number
            ans += i;
 
            // Decrease the number
            arr[i]--;
 
            // Perform the DFS Call
            DFS(arr, ans);
            ans = ans.substring(
                0, ans.length() - 1);
 
            // Backtracking the frequency
            arr[i]++;
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String number = "123";
 
        int count[] = new int[10];
        for (int i = 0; i < number.length(); ++i) {
            count[number.charAt(i) - 48]++;
        }
 
        // Perform the DFS Traversal
        DFS(count, "");
 
        // Print the result
        System.out.println(H.size());
    }
}

Python3




H = set()
  
# Function to check whether the
# number is prime or not
def check(number):
    if (len(number) == 0):
        return False
    num = int(number)
  
    # Condition for prime number
    if (num == 1):
        return False
    if (num % 2 == 0 and num != 2):
        return False
    if (num % 3 == 0 and num != 3):
        return False
  
    # Iterate over the range [6, num]
    i = 6
    while(i * i <= num):
        if (num % (i - 1) == 0 or num % (i + 1) == 0):
            return False
        i = i + 6
  
    # Otherwisem return true
    return True
  
# Function to count the total number
# of prime numbers
def DFS(arr, ans):
    # Add it in the HashSet
    if (check(ans)):
        H.add(ans)
  
    for i in range(10):
        if (arr[i] == 0):
            continue
  
        # Use the number
        ans = (ans + str(i))
  
        # Decrease the number
        arr[i] -= 1
  
        # Perform the DFS Call
        DFS(arr, ans)
        ans = ans[0: len(ans) - 1]
  
        # Backtracking the frequency
        arr[i]+=1
 
number = "123"
count = [0]*(10)
for i in range(10):
    count[i] = 0
for i in range(len(number)):
    count[ord(number[i]) - ord('0')] += 1
H.clear()
DFS(count, "")
print(len(H))
 
# This code is contributed by divyesh072019.

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
    static HashSet<String> H = new HashSet<String>();
 
    // Function to check whether the
    // number is prime or not
    static bool check(String number)
    {
        if (number.Length == 0) {
            return false;
        }
        number = number.Trim();
        long num = long.Parse(number);
 
        // Condition for prime number
        if (num == 1) {
            return false;
        }
        if (num % 2 == 0 && num != 2) {
            return false;
        }
        if (num % 3 == 0 && num != 3) {
            return false;
        }
 
        // Iterate over the range [6, num]
        for (int i = 6; i * i <= num; i += 6) {
            if (num % (i - 1) == 0 || num % (i + 1) == 0) {
                return false;
            }
        }
 
        // Otherwisem return true
        return true;
    }
 
    // Function to count the total number
    // of prime numbers
    static void DFS(int []arr, String ans)
    {
        // Add it in the HashSet
        if (check(ans) == true) {
            H.Add(ans);
        }
 
        for (int i = 0; i <= 9; ++i) {
            if (arr[i] == 0) {
                continue;
            }
 
            // Use the number
            ans += i;
 
            // Decrease the number
            arr[i]--;
 
            // Perform the DFS Call
            DFS(arr, ans);
            ans = ans.Substring(
                0, ans.Length - 1);
 
            // Backtracking the frequency
            arr[i]++;
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String number = "123";
 
        int []count = new int[10];
        for (int i = 0; i < number.Length; ++i) {
            count[number[i] - 48]++;
        }
 
        // Perform the DFS Traversal
        DFS(count, "");
 
        // Print the result
        Console.WriteLine(H.Count);
    }
}
 
// This code contributed by shikhasingrajput.

Javascript




<script>
    // Javascript program for the above approach
     
    let H = new Set();
     
    // Function to check whether the
    // number is prime or not
    function check(number)
    {
        if (number.length == 0) {
            return false;
        }
        let num = parseInt(number);
 
        // Condition for prime number
        if (num == 1) {
            return false;
        }
        if (num % 2 == 0 && num != 2) {
            return false;
        }
        if (num % 3 == 0 && num != 3) {
            return false;
        }
 
        // Iterate over the range [6, num]
        for (let i = 6; i * i <= num; i += 6) {
            if (num % (i - 1) == 0 || num % (i + 1) == 0) {
                return false;
            }
        }
 
        // Otherwisem return true
        return true;
    }
 
    // Function to count the total number
    // of prime numbers
    function DFS(arr, ans)
    {
        // Add it in the HashSet
        if (check(ans)) {
            H.add(ans);
        }
 
        for (let i = 0; i <= 9; ++i) {
            if (arr[i] == 0) {
                continue;
            }
 
            // Use the number
            ans = (ans + i.toString());
 
            // Decrease the number
            arr[i]--;
 
            // Perform the DFS Call
            DFS(arr, ans);
            ans = ans.substring(0, ans.length - 1);
 
            // Backtracking the frequency
            arr[i]++;
        }
    }
     
    let number = "123";
    let count = new Array(10);
    for (let i = 0; i < 10; i++) {
        count[i] = 0;
    }
    for (let i = 0; i < number.length; i++) {
        count[number[i] - '0']++;
    }
    H.clear();
    DFS(count, "");
    document.write(H.size);
 
// This code is contributed by decode2207.
</script>
Output: 
5

 

Time Complexity: O(9N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :