Count all prime numbers that can be formed using digits of a given number
Input: S = “123”
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”
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:
- 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.
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.