给定一个整数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
Javascript
输出:
7.2 1.2
时间复杂度: O(1)
辅助空间; O(1)