Count numbers in range whose sum of digits is divisible by XOR of digits
Given integers L and R, the task for this problem is to find a number of integers in the range L to R whose sum of digits is divisible by bitwise XOR of digits. print the answer. ( L <= R <= 1018)
Note: Bitwise XOR sum zero never divides any other number.
Input: L = 10, R = 15
- Number 10 : digitSum = 1 + 0 = 1, xorSum = 1 ^ 0 = 1, included in answer, 1 % 1 = 0
- Number 11: digitSum = 1 + 1 = 2, xorSum = 1 ^ 1 = 0, not included in answer since bitwise XOR sum is zero.
- Number 12: digitSum = 1 + 2 = 3, xorSum = 1 ^ 2 = 3, included in answer since 2 % 1 = 0
- Number 13: digitSum = 1 + 3 = 4, xorSum = 1 ^ 3 = 2, included in answer since 4 % 2 = 0
- Number 14: digitSum = 1 + 4 = 5, xorSum = 1 ^ 4 = 5, included in answer since 5 % 5 = 0
- Number 15: digitSum = 1 + 5 = 6, xorSum = 1 ^ 5 = 4, not included in answer since 6 % 4 != 0
10, 12, 13 and 14 are the numbers whose sum of digits are divisible by bitwise XOR sum of digits
Input: L = 1, R = 100
Naive approach: The basic way to solve the problem is as follows:
The basic way to solve this problem is to generate all possible combinations by using a recursive approach.
Time Complexity: O(18N), Where N is the number of digits to be filled.
Auxiliary Space: O(1)
Efficient Approach: Dynamic programming can be used to solve this problem:
- dp[i][j][k][l] represents numbers in the range with i digits, j represents tight condition, k represents current sum and l represents bitwise XOR sum.
- It can be observed that the recursive function is called exponential times. That means that some states are called repeatedly.
- So the idea is to store the value of each state. This can be done using by storing the value of a state and whenever the function is called, returning the stored value without computing again.
- First answer will be calculated for 0 to L – 1 and then calculated for 0 to R then the latter one is subtracted from the prior one to get answer for range [L, R].
Follow the steps below to solve the problem:
- Create a recursive function that takes four parameters i representing the position to be filled, j representing a tight condition, k representing the sum of digits, and finally l containing bitwise XOR sum of digits.
- Call the recursive function for choosing all digits from 0 to 9.
- Base case if the size of the digit is N and the sum is divisible by bitwise XOR sum return 1 else returns 0.
- Create a 4d array dp initially filled with -1.
- If the answer for a particular state is computed then save it in dp[i][j][k][l].
- if the answer for a particular state is already computed then just return dp[i][j][k][l].
Below is the implementation of the above approach:
Time Complexity: O(log(R) * M * N), where M is the maximum sum of digits and N is the maximum bitwise XOR sum of digits
Auxiliary Space: O(log(R) * M * N)
Please Login to comment...