Open In App

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

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:

Below is the implementation of the above approach.




#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 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());
    }
}




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# 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.




<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)


Article Tags :