Count of pairs of integers up to X and Y that generates equal Quotient and Remainder
Last Updated :
27 Aug, 2021
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.
Examples:
Input: X = 4, Y = 5
Output: 2
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.
C++
#include <bits/stdc++.h>
using namespace std;
void countOfPairs( int x, int y)
{
int count = 0;
for ( int k = 1; k * k <= x; ++k) {
count += max(0, min(y, x / k - 1) - k);
}
cout << count << "\n" ;
}
int main()
{
int x = 4;
int y = 5;
countOfPairs(x, y);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void countOfPairs( int x, int y)
{
int count = 0 ;
for ( int k = 1 ; k * k <= x; ++k) {
count
+= Math.max(
0 , Math.min(y, x / k - 1 ) - k);
}
System.out.print(count);
}
public static void main(String[] args)
{
int x = 4 ;
int y = 5 ;
countOfPairs(x, y);
}
}
|
Python3
from math import sqrt
def countOfPairs(x, y):
count = 0
for k in range ( 1 , int (sqrt(x)) + 1 , 1 ):
count + = max ( 0 , min (y, x / k - 1 ) - k)
print ( int (count))
if __name__ = = '__main__' :
x = 4
y = 5
countOfPairs(x, y)
|
C#
using System;
public class GFG {
static void countOfPairs( int x, int y)
{
int count = 0;
for ( int k = 1; k * k <= x; ++k) {
count
+= Math.Max(
0, Math.Min(y, x / k - 1) - k);
}
Console.Write(count);
}
static public void Main()
{
int x = 4;
int y = 5;
countOfPairs(x, y);
}
}
|
Javascript
<script>
function countOfPairs(x, y)
{
var count = 0;
var k;
for (k = 1; k * k <= x; ++k) {
count += Math.max(0, Math.min(y, x / k - 1) - k);
}
document.write(count + "<br>" );
}
var x = 4;
var y = 5;
countOfPairs(x, y);
</script>
|
Time Complexity: O(?X)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...