Find two numbers with sum and product both same as N
Last Updated :
11 Jul, 2022
Given an integer N, the task is to find two numbers a and b such that a * b = N and a + b = N. Print “NO” if no such numbers are possible.
Examples:
Input: N = 69
Output: a = 67.9851
b = 1.01493
Input: N = 1
Output: NO
Approach: If observed carefully, we are given with sum and product of roots of a quadratic equation.
If N2 – 4*N < 0 then only imaginary roots are possible for the equation, hence “NO” will be the answer. Else a and b will be:
a = ( N + sqrt( N2 – 4*N ) ) / 2
b = ( N – sqrt( N2 – 4*N ) ) / 2
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findAandB( double N)
{
double val = N * N - 4.0 * N;
if (val < 0) {
cout << "NO" ;
return ;
}
double a = (N + sqrt (val)) / 2.0;
double b = (N - sqrt (val)) / 2.0;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
int main()
{
double N = 69.0;
findAandB(N);
return 0;
}
|
Java
class GFG{
static void findAandB( double N)
{
double val = N * N - 4.0 * N;
if (val < 0 ) {
System.out.println( "NO" );
return ;
}
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);
}
public static void main(String[] args)
{
double N = 69.0 ;
findAandB(N);
}
}
|
Python3
from math import sqrt
def findAandB(N):
val = N * N - 4.0 * N
if (val < 0 ):
print ( "NO" )
return
a = (N + sqrt(val)) / 2.0
b = (N - sqrt(val)) / 2.0
print ( "a =" , '{0:.6}' . format (a))
print ( "b =" , '{0:.6}' . format (b))
if __name__ = = '__main__' :
N = 69.0
findAandB(N)
|
C#
using System;
class GFG
{
static void findAandB( double N)
{
double val = N * N - 4.0 * N;
if (val < 0) {
Console.WriteLine( "NO" );
return ;
}
double a = (N + Math.Sqrt(val)) / 2.0;
double b = (N - Math.Sqrt(val)) / 2.0;
Console.WriteLine( "a = " +a);
Console.WriteLine( "b = " +b);
}
static void Main()
{
double N = 69.0;
findAandB(N);
}
}
|
PHP
<?php
function findAandB( $N )
{
$val = $N * $N - 4.0 * $N ;
if ( $val < 0)
{
echo "NO" ;
return ;
}
$a = ( $N + sqrt( $val )) / 2.0;
$b = ( $N - sqrt( $val )) / 2.0;
echo "a = " , $a , "\n" ;
echo "b = " , $b , "\n" ;
}
$N = 69.0;
findAandB( $N );
?>
|
Javascript
<script>
function findAandB(N)
{
let val = N * N - 4.0 * N;
if (val < 0) {
document.write( "NO" );
return ;
}
let a = (N + Math.sqrt(val)) / 2.0;
let b = (N - Math.sqrt(val)) / 2.0;
document.write( "a = " +a.toFixed(4) + "</br>" );
document.write( "b = " +b.toFixed(5));
}
let N = 69.0;
findAandB(N);
</script>
|
Output:
a = 67.9851
b = 1.01493
Time Complexity: O(logn2)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...