给定一个整数N ,任务是找到两个数字a和b ,使得a * b = N和a + b = N。如果没有这样的数字,请打印“ NO”。
例子:
Input: N = 69
Output: a = 67.9851
b = 1.01493
Input: N = 1
Output: NO
方法:如果仔细观察,我们将得到二次方程根的和与乘积。
如果N 2 – 4 * N <0,则方程只有虚数根,因此“ NO”将是答案。其他a和b将是:
a = ( N + sqrt( N2 – 4*N ) ) / 2
b = ( N – sqrt( N2 – 4*N ) ) / 2
下面是上述方法的实现:
C++
// C++ program to find a and b
// such that a*b=N and a+b=N
#include
using namespace std;
// Function to return the smallest string
void findAandB(double N)
{
double val = N * N - 4.0 * N;
// Not possible
if (val < 0) {
cout << "NO";
return;
}
// find a and b
double a = (N + sqrt(val)) / 2.0;
double b = (N - sqrt(val)) / 2.0;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
// Driver Code
int main()
{
double N = 69.0;
findAandB(N);
return 0;
}
Java
// Java program to find a and b
// such that a*b=N and a+b=N
class GFG{
// Function to return the smallest string
static void findAandB(double N)
{
double val = N * N - 4.0 * N;
// Not possible
if (val < 0) {
System.out.println("NO");
return;
}
// find a and b
double a = (N + Math.sqrt(val)) / 2.0;
double b = (N - Math.sqrt(val)) / 2.0;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
// Driver Code
public static void main(String[] args)
{
double N = 69.0;
findAandB(N);
}
}
// This Code is contributed by mits
Python3
# Python 3 program to find a and b
# such that a*b=N and a+b=N
from math import sqrt
# Function to return the
# smallest string
def findAandB(N):
val = N * N - 4.0 * N
# Not possible
if (val < 0):
print("NO")
return
# find a and b
a = (N + sqrt(val)) / 2.0
b = (N - sqrt(val)) / 2.0
print("a =", '{0:.6}' . format(a))
print("b =", '{0:.6}' . format(b))
# Driver Code
if __name__ == '__main__':
N = 69.0
findAandB(N)
# This code is contributed
# by SURENDRA_GANGWAR
C#
// C# program to find a and b
// such that a*b=N and a+b=N
using System;
class GFG
{
// Function to return the smallest string
static void findAandB(double N)
{
double val = N * N - 4.0 * N;
// Not possible
if (val < 0) {
Console.WriteLine("NO");
return;
}
// find a and b
double a = (N + Math.Sqrt(val)) / 2.0;
double b = (N - Math.Sqrt(val)) / 2.0;
Console.WriteLine("a = "+a);
Console.WriteLine("b = "+b);
}
// Driver Code
static void Main()
{
double N = 69.0;
findAandB(N);
}
// This code is contributed by ANKITRAI1
}
PHP
输出:
a = 67.9851
b = 1.01493