Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions.
Input: L = 5, R = 22
Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions.
Input: L = 20, R = 29
Explanation: There are no numbers which have prime digits at prime positions and non-prime digits at non-prime positions.
Naive Approach: The simplest approach to solve the problem is to iterate over the range [L, R]. For every ith number check if the digits of the number is prime at prime positions and non-prime at non-prime positions or not. If found to be true, then increment the count. Finally, print the count obtained.
Time Complexity: O(R – L + 1) * sqrt(R) * log10(R)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Digit DP. Following are the recurrence relation between the dynamic programming states:
If i is a prime at prime digits or non-prime at non-prime digits, then x = 1
pos: Stores position of digits
prime: Check if prime digits are present at prime positions and non-prime digits at non-prime positions are present or not.
st: check if a number contains any leading 0.
end: Maximum possible digits at current position
Follow the steps below to solve the problem:
- Initialize a 4D array, say dp[pos][st][tight][prime].
- Compute the value of dp[pos][st][tight][prime] for the number R using memorization, say cntR.
- Compute the value of dp[pos][st][tight][prime] for the number L – 1 using memorization, say cntL.
- Finally, print the value of (cntR – cntL).
Below is the implementation of the above approach:
Time Complexity: O(log10(R) * log10(L) sqrt(log10(R))* 10 * 4))
Auxiliary Space: O(log10(R) * log10(L) * 4)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.