Given a range of values [L, R] and a value K, the task is to count the numbers in the given range which are divisible by at least K of the digits present in the decimal representation of that number.
Input: L = 24, R = 25, K = 2
24 has two digits 2 and 4 and is divisible by both 2 and 4. So this satisfies the given condition.
25 has two digits 2 and 5 and is only divisible by 5. But since K = 2, it doesnot qualifies the mentioned criteria.
Input: L = 5, R = 15, K = 1
Method 1: Naive Approach
- For any number between L to R, find the count of it’s digits that divides the number.
- If the count of number in the above step is greater than or equal to K, then include that number to the final count.
- Repeat the above steps for all numbers from L to R and print the final count.
Time Complexity: O(N), where N is the difference between the range [L, R].
Method 2: Efficient Approach
We will use the concept of Digit DP to solve this problem. Below are the observations to solve this problem:
- For all the positive integers(say a), to find the divisibility of the number from digits 2 to 9, the number a can be reduced as stated below to find the divisibility efficiently:
a = k*LCM(2, 3, 4, ..., 9) + q where k is integer and q lies between range [0, lcm(2, 3, ..9)] LCM(2, 3, 4, ..., 9) = 23x32x5x7 = 2520
- After performing a = a modulo 2520, we can find the count of digit from the original number a that divides this modulo.
Below are the steps to do so:
- Store all the digits of the given range and sort the digits in decreasing order.
- Traverse all the digits stored above and generate all the number which are strictly less than the given range of number.
- For generating the number less than the given number, use a variable tight such that:
- The value of tight is 0, denotes that by including that digit will give the number less than the given range.
- The value of tight is 1, denotes that by including that digit, it will give the number greater than the given range. So we can remove all permutations after getting tight value 1 to avoid more number of recursive calls.
- After generating all of the permutations of numbers, Find the number for which the count of digits dividing that number is greater than or equals to K.
- Store the count for each permuted number in dp table to use the result for Overlapping Subproblems.
Below is the implementation of the above approach:
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.