Count of pairs of integers up to X and Y that generates equal Quotient and Remainder
Given two integers X and Y, the task is to count the number of pairs (m, n), such that m / n = m % n and 1 ≤ m ≤ x and 1 ≤ n ≤ y.
Input: X = 4, Y = 5
Explanation: The pairs (3, 2) and (4, 3) satisfy the condition.
Input: X = 3, Y = 1
Output : 0
Approach: The given problem can be solved based on the following observations:
- For the condition to be satisfied, the numerator must be of the form (kn + k). Therefore, (kn + k) / n = (kn + k) % n = k.
- It also implies that k < n. Therefore, k * k < k * n + k <= x. Hence, k < sqrt(x).
- Therefore, iterating from 1 to sqrt(x) for the numerator is sufficient.
- Rewriting k * n + k ≤ x gives us n <= (x / k – 1) . Also, n > k and n <= y from the constraints.
- For each possible numerator value, count the possible denominator values and update the total count.
Below is the implementation of the above approach.
Time Complexity: O(√X)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.