Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
Given a range [L, R]. The task is to count the numbers in the range having difference between the sum of digits at even position and sum of digits at odd position is a Prime Number. Consider the position of least significant digit in the number as an odd position.
Input : L = 1, R = 50 Output : 6 Explanation : Only, 20, 30, 31, 41, 42 and 50 are valid numbers. Input : L = 50, R = 100 Output : 18
Prerequisites: Digit DP
Approach: Firstly, if we are able to count the required numbers up to R i.e. in the range [0, R], we can easily reach our answer in the range [L, R] by solving for from zero to R and then subtracting the answer we get after solving from zero to L – 1. Now, we need to define the DP states.
- Since we can consider our number as a sequence of digits, one state is the position at which we are currently at. This position can have values from 0 to 18 if we are dealing with numbers up to 1018. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9.
- First state is the sum of the digits at even positions we have placed so far.
- Second state is the sum of the digits at odd positions we have placed so far.
- Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, the maximum limit of digit we can place is digit at the current position in R.
Also, when we reach the base condition, we need to check whether the required difference is a prime number or not. Since the highest number in range is 1018, the maximum sum at either even or odd positions can be at max 9 times 9 and hence the maximum difference. So, we need to check only prime numbers only upto 100 at base condition.
Below is the implementation of the above approach:
Time Complexity: O(pos*limit)
Auxiliary Space: O(M*90*90*2)