![]() |
VOOZH | about |
Given a positive integer n, the task is to count the number of n digits numbers which contain all single digit primes.
Examples:
Input: n = 4
Output: 24
Explanation: The number of single digit primes is 4 i.e.[2, 3, 5, 7]. Hence number of ways to arrange 4 numbers in 4 places is 4! = 24.Input: n = 5
Output: 936
The simplest approach to solve the given problem is to generate all possible n-digit numbers and count those numbers which contain all single-digit prime numbers. After checking for all the numbers, print the value of the count as the resultant total count of numbers.
To solve this, we generate all possible n-digit numbers recursively while keeping track of which single-digit primes have been encountered so far using a bitmask. Since there are only 4 single-digit primes, we can represent their presence using 4 bits:
Mapping primes to bits:
- 2 is mapped to bit 0
- 3 is mapped to bit 1
- 5 is mapped to bit 2
- 7 is mapped to bit 3
The bitmask allows us to efficiently track these primes. For example, if the current digit is 7, we update the bitmask as mask | (1<<3) where (1<<3) set 3rd bit to 1. since 7 is mapped to 3, we set 3rd bit to 1.
Recursive Relation:
For a given index i, we iterate over all digits from 0 to 9, take the summation of it.
countOfNumbers(i, mask, n) = countOfNumbers(i+1, newMask, n) for all value of d from 0 to 9.
- If d is a prime number (d ∈ {2, 3, 5, 7}), update the bitmask to include d:
newMask = (mask | (1<<primeIndex[d]))
where, primeIndex[d] is the mapped number given to d (primeIndex[2] = 0, primeIndex[3] = 1, primeIndex[5] = 2, primeIndex[7]=3)- otherwise, the bitmak remains unchanged:
newMask = maskBase Case:
if i = n+1 where n is the total number of digits.
countOfNumbers(i, mask, n) = 1 , if count of set bits in mask is 4(all the single digit prime number is present) otherwise 0.
24
Time Complexity: O(n *10^n)
Auxiliary Space: O(n)
If notice carefully, we can see that the above recursive function countOfNumbers() also follows the overlapping subproblems property i.e., same substructure solved again and again in different recursion call paths. We can avoid this using the memoization approach. Since there is two parameter that changes in recursive calls so we use a 2D array and initialize it as -1 to indicate that the values are not computed.
24
Time Complexity: O(10*n*2^4)
Auxiliary Space: O(n*2^4)
The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.
24
Time Complexity: O(10*n*2^4)
Auxiliary Space: O(n*2^4)