Count of Ordered Pairs (X, Y) satisfying the Equation 1/X + 1/Y = 1/N
Given a positive integer N, the task is to find the number of ordered pairs (X, Y) where both X and Y are positive integers, such that they satisfy the equation 1/X + 1/Y = 1/N.
Examples:
Input: N = 5
Output: 3
Explanation: Only 3 pairs {(30,6), (10,10), (6,30)} satisfy the given equation.
Input: N = 360
Output: 105
Approach:
Follow the steps to solve the problem:
- Solve for X using the given equation.
1/X + 1/Y = 1/N
=> 1/X = 1/N – 1/Y
=> 1/X = (Y – N) / NY
=> X = NY / (Y – N)
X = [ NY / (Y – N) ] * (1)
=> X = [ NY / (Y – N) ] * [1 – N/Y + N/Y]
=> X = [ NY / (Y – N) ] * [(Y- N)/Y + N/Y]
=> X = N + N2 / (Y – N)
- Therefore, it can be observed that, to have a positive integer X, the remainder when N2 is divided by (Y – N) needs to be 0.
- It can be observed that the minimum value of Y can be N + 1 (so that denominator Y – N > 0) and the maximum value of Y can be N2 + N so that N2/(Y – N) remains a positive integer ? 1.
- Then iterate over the maximum and minimum possible values of Y, and for each value of Y for which N2 % (Y – N) == 0, increment count.
- Finally, return count as the number of ordered pairs.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void solve( int n)
{
int ans = 0;
for ( int y = n + 1; y <= n * n + n; y++) {
if ((n * n) % (y - n) == 0) {
ans += 1;
}
}
cout << ans;
}
int main()
{
int n = 5;
solve(n);
return 0;
}
|
Java
class GFG{
static void solve( int n)
{
int ans = 0 ;
for ( int y = n + 1 ; y <= n * n + n; y++)
{
if ((n * n) % (y - n) == 0 )
{
ans += 1 ;
}
}
System.out.print(ans);
}
public static void main(String[] args)
{
int n = 5 ;
solve(n);
}
}
|
Python3
def solve(n):
ans = 0
y = n + 1
while (y < = n * n + n):
if ((n * n) % (y - n) = = 0 ):
ans + = 1
y + = 1
print (ans)
n = 5
solve(n)
|
C#
using System;
class GFG{
static void solve( int n)
{
int ans = 0;
for ( int y = n + 1; y <= n * n + n; y++)
{
if ((n * n) % (y - n) == 0)
{
ans += 1;
}
}
Console.Write(ans);
}
public static void Main(String[] args)
{
int n = 5;
solve(n);
}
}
|
Javascript
<script>
function solve(n) {
var ans = 0;
for (y = n + 1; y <= n * n + n; y++) {
if ((n * n) % (y - n) == 0) {
ans += 1;
}
}
document.write(ans);
}
var n = 5;
solve(n);
</script>
|
Output:
3
Time Complexity: O(N2)
Auxiliary Space: O(1)
Last Updated :
08 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...