Count of pairs from first N natural numbers with remainder at least K
Given two positive integers N and K, the task is to find the number of pairs (a, b) over the range [1, N] such that a%b is at least K.
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.
Input: N = 5, K = 2
Following are the all possible pairs satisfying the given criteria:
- (2, 3): The value of 2%3 = 2(>= K).
- (5, 3): The value of 5%3 = 2(>= K).
- (2, 4): The value of 2%4 = 2(>= K).
- (3, 4): The value of 3%4 = 3(>= K).
- (2, 5): The value of 2%5 = 2(>= K).
- (3, 5): The value of 3%5 = 3(>= K).
- (4, 5): The value of 4%5 = 4(>= K).
Therefore, the total count of pairs is 7.
Input: N = 6, K = 0
Naive Approach: The simplest approach to solve the given problem is to generate all possible pairs (a, b) over the range [1, N] and if the value of a%b is at least K, then count this pair. After checking for all the pairs, print the total pairs obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by iterating over the range [1, N] and fix the second number in the pair, i.e., b. For each fixed b there will be a period of N/b and every period can be combiner with (b – K) elements. So, a total of (N/b)*(b – K) elements will be there. Now for the remaining elements that are N%b there will be max(0, n%b – k + 1) pairs. Follow the steps below to solve the problem:
- If the value of K is 0, then print N2 as the resultant number of valid pairs.
- Initialize the variable, say ans as 0 that stores the resultant count of pairs.
- Iterate over the range [K + 1, N] using the variable b and perform the following steps:
- Add the value of (N/b)*(b – K) to the variable ans.
- Add the value of the maximum of (N % b – K + 1) or 0 to the variable ans.
- After performing the above steps, print the value of ans as the resultant count of pairs.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)