📌  相关文章
📜  一对具有差异 K 的整数,其中一个元素是另一个的第 K 倍

📅  最后修改于: 2021-10-26 05:57:59             🧑  作者: Mango

给定一个整数K ,任务是找到一对数字(A, B)使得A – B = KA / B = K。如果不能生成这样的对,则打印“No”

例子:

方法:
为了解决这个问题,需要进行以下观察:

  • 给定的条件可以写成等式的形式:
    1. 等式 (1): A – B = K => A – B – K = 0
    2. 等式 (2): A / B = K => A – (K * B) = 0
  • 求解这两个方程,我们得到:
  • 代入式(1)中A的值,可得B的值为K / (K – 1)
  • 可以观察到,如果K 的值为1 ,则由于AB分母都变为 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)