给定整数K ,任务是找到一对数字(A,B) ,使A – B = K并且A / B =K。如果无法生成这样的对,则打印“ No” 。
例子:
Input: K = 6
Output: 7.2 1.2
Explanation:
Since 7.2 – 1.2 = 6 and 7.2 / 1.2 = 6, The pair {7.2, 1.2} satisfy the necessary conditions.
Input: K = 1
Output: No
方法:
需要解决以下问题:
- 给定的条件可以用等式的形式写成:
- 公式(1): A – B = K => A – B – K = 0
- 公式(2): A / B = K => A –(K * B)= 0
- 求解这两个方程,我们得到:
( K * Equation (1) ) – Equation(2) = 0
=> K*A – K*B – K2 – (A – K*B) = 0
=> K*A – K2 – A – K*B + K*B = 0
=> A*(K-1) – K2 = 0
=> A*(K-1) = K2
=> A = K2 / (K -1)
- 替换公式(1)中的A值,可以得出B的值为K /(K – 1)
- 可以观察到,如果K的值为1 ,则找不到这样的对,因为A和B的分母都变为0。
请按照以下步骤解决问题:
- 如果K等于1 ,则打印“ NO” 。
- 否则,如果K等于0以外的任何其他值,则计算(K * K)/(K -1)和K /(K – 1)的值并打印出来。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above problem
#include
using namespace std;
// Function to find the
// required pair
void computePair(double K)
{
// No pair possible
if (K == 1) {
cout << "No";
return;
}
else {
cout << K * K / (K - 1) << " ";
cout << K / (K - 1) << endl;
}
}
// Driver Code
int main()
{
double K = 6;
computePair(K);
return 0;
}
Java
// Java program to implement
// the above problem
class GFG{
// Function to find the
// required pair
static void computePair(double K)
{
// No pair possible
if (K == 1)
{
System.out.print("No");
return;
}
else
{
System.out.print(K * K / (K - 1) + " ");
System.out.print(K / (K - 1) + "\n");
}
}
// Driver Code
public static void main(String[] args)
{
double K = 6;
computePair(K);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to implement
# the above problem
# Function to find the
# required pair
def computePair(K):
# No pair possible
if (K == 1):
print("No")
return
else:
print(K * K / (K - 1), end = " ")
print(K / (K - 1))
# Driver Code
if __name__ == "__main__":
K = 6
computePair(K)
# This code is contributed by chitranayal
C#
// C# program to implement
// the above problem
using System;
class GFG{
// Function to find the
// required pair
static void computePair(double K)
{
// No pair possible
if (K == 1)
{
Console.Write("No");
return;
}
else
{
Console.Write(K * K / (K - 1) + " ");
Console.Write(K / (K - 1) + "\n");
}
}
// Driver Code
public static void Main(String[] args)
{
double K = 6;
computePair(K);
}
}
// This code is contributed by gauravrajput1
输出:
7.2 1.2
时间复杂度: O(1)
辅助空间; O(1)