给定正整数N ,任务是查找有序对(X,Y)的数量,其中X和Y均为正整数,这样它们满足方程1 / X + 1 / Y = 1 / N。
例子:
Input: N = 5
Output: 3
Explanation: Only 3 pairs {(30,6), (10,10), (6,30)} satisfy the given equation.
Input: N = 360
Output: 105
方法:
请按照以下步骤解决问题:
- 使用给定的方程式求解X。
1/X + 1/Y = 1/N
=> 1/X = 1/N – 1/Y
=> 1/X = (Y – N) / NY
=> X = NY / (Y – N)
=> X = N + N2 / (Y – N)
- 因此,可以看出,要有一个正整数X , N 2除以(Y – N)时的余数必须为0 。
- 可以看出, Y的最小值可以为N + 1 (因此分母Y – N> 0) , Y的最大值可以为N 2 + N,从而N 2 /(Y – N)保持为正整数≥1 。
- 然后遍历最大和Y的最小可能值,并且用于Y的各值,对于这个N 2%(Y – N)== 0,递增计数。
- 最后,将count作为有序对的数量返回。
下面是上述方法的实现:
C++
// C++ Program for the above approach
#include
using namespace std;
// Function to find number of ordered
// positive integer pairs (x,y) such
// that they satisfy the equation
void solve(int n)
{
// Initialize answer variable
int ans = 0;
// Iterate over all possible values of y
for (int y = n + 1; y <= n * n + n; y++) {
// For valid x and y,
// (n*n)%(y - n) has to be 0
if ((n * n) % (y - n) == 0) {
// Increment count of ordered pairs
ans += 1;
}
}
// Print the answer
cout << ans;
}
// Driver Code
int main()
{
int n = 5;
// Function call
solve(n);
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function to find number of ordered
// positive integer pairs (x,y) such
// that they satisfy the equation
static void solve(int n)
{
// Initialize answer variable
int ans = 0;
// Iterate over all possible values of y
for(int y = n + 1; y <= n * n + n; y++)
{
// For valid x and y,
// (n*n)%(y - n) has to be 0
if ((n * n) % (y - n) == 0)
{
// Increment count of ordered pairs
ans += 1;
}
}
// Print the answer
System.out.print(ans);
}
// Driver Code
public static void main(String[] args)
{
int n = 5;
// Function call
solve(n);
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program for the above approach
# Function to find number of ordered
# positive integer pairs (x,y) such
# that they satisfy the equation
def solve(n):
# Initialize answer variable
ans = 0
# Iterate over all possible values of y
y = n + 1
while(y <= n * n + n):
# For valid x and y,
# (n*n)%(y - n) has to be 0
if ((n * n) % (y - n) == 0):
# Increment count of ordered pairs
ans += 1
y += 1
# Print the answer
print(ans)
# Driver Code
n = 5
# Function call
solve(n)
# This code is contributed by Shivam Singh
C#
// C# program for the above approach
using System;
class GFG{
// Function to find number of ordered
// positive integer pairs (x,y) such
// that they satisfy the equation
static void solve(int n)
{
// Initialize answer variable
int ans = 0;
// Iterate over all possible values of y
for(int y = n + 1; y <= n * n + n; y++)
{
// For valid x and y,
// (n*n)%(y - n) has to be 0
if ((n * n) % (y - n) == 0)
{
// Increment count of ordered pairs
ans += 1;
}
}
// Print the answer
Console.Write(ans);
}
// Driver Code
public static void Main(String[] args)
{
int n = 5;
// Function call
solve(n);
}
}
// This code is contributed by Amit Katiyar
输出:
3
时间复杂度: O(logN)
辅助空间: O(1)