📌  相关文章
📜  找到两个与 N 相同的差和除法的数字

📅  最后修改于: 2021-10-27 06:20:42             🧑  作者: Mango

给定一个整数 N ,任务是找到两个数字 a 和 b ,使得a / b = Na – b = N 。如果不可能有这样的数字,请打印“否”
例子:

方法:要解决这个问题,请观察下面推导出的方程:

同时求解上述方程,我们得到:

由于分母是N – 1 ,所以当N = 1时,答案是不可能的。对于所有其他情况,答案是可能的。因此,分别求出 a 和 b 的值。
下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find two numbers with
// difference and division both as N
void findAandB(double N)
{
    // Condition if the answer
    // is not possible
 
    if (N == 1) {
        cout << "No";
        return;
    }
 
    // Calculate a and b
    double a = N * N / (N - 1);
    double b = a / N;
 
    // Print the values
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}
 
// Driver Code
int main()
{
    // Given N
    double N = 6;
 
    // Function Call
    findAandB(N);
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function to find two numbers with
// difference and division both as N
static void findAandB(double N)
{
     
    // Condition if the answer
    // is not possible
    if (N == 1)
    {
        System.out.print("No");
        return;
    }
 
    // Calculate a and b
    double a = N * N / (N - 1);
    double b = a / N;
 
    // Print the values
    System.out.print("a = " + a + "\n");
    System.out.print("b = " + b + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given N
    double N = 6;
 
    // Function call
    findAandB(N);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Function to find two numbers with
# difference and division both as N
def findAandB(N):
     
    # Condition if the answer
    # is not possible
    if (N == 1):
        print("No")
        return
     
    # Calculate a and b
    a = N * N / (N - 1)
    b = a / N
 
    # Print the values
    print("a = ", a)
    print("b = ", b)
 
# Driver Code
 
# Given N
N = 6
 
# Function call
findAandB(N)
 
# This code is contributed by sanjoy_62


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to find two numbers with
// difference and division both as N
static void findAandB(double N)
{
 
    // Condition if the answer
    // is not possible
    if (N == 1)
    {
        Console.Write("No");
        return;
    }
 
    // Calculate a and b
    double a = N * N / (N - 1);
    double b = a / N;
 
    // Print the values
    Console.Write("a = " + a + "\n");
    Console.Write("b = " + b + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
 
    // Given N
    double N = 6;
 
    // Function call
    findAandB(N);
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
a = 7.2
b = 1.2

时间复杂度: O(1)
辅助空间: O(1)