Pair of integers with difference K having an element as the K-th multiple of the other
Last Updated :
22 Apr, 2021
Given an integer K, the task is to find a pair of numbers (A, B) such that A – B = K and A / B = K. If no such pair can be generated, print “No”.
Examples:
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
Approach:
The following observations are needed to be made to solve the problem:
- The given conditions can be written in the form of equations as:
- Equation (1): A – B = K => A – B – K = 0
- Equation (2): A / B = K => A – (K * B) = 0
- Solving both these equations, we obtain:
( 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)
- Replacing the value of A in Equation (1), the value of B can be obtained to be K / (K – 1)
- It can be observed that if the value of K is 1, then no such pair can be found as the denominator of both A and B becomes 0.
Follow the steps below to solve the problem:
- If K is equal to 1, then print “NO”.
- Otherwise, if K is equal to any value other than 0, compute the values (K*K) / (K -1) and K / (K – 1) and print them.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void computePair( double K)
{
if (K == 1) {
cout << "No" ;
return ;
}
else {
cout << K * K / (K - 1) << " " ;
cout << K / (K - 1) << endl;
}
}
int main()
{
double K = 6;
computePair(K);
return 0;
}
|
Java
class GFG{
static void computePair( double K)
{
if (K == 1 )
{
System.out.print( "No" );
return ;
}
else
{
System.out.print(K * K / (K - 1 ) + " " );
System.out.print(K / (K - 1 ) + "\n" );
}
}
public static void main(String[] args)
{
double K = 6 ;
computePair(K);
}
}
|
Python3
def computePair(K):
if (K = = 1 ):
print ( "No" )
return
else :
print (K * K / (K - 1 ), end = " " )
print (K / (K - 1 ))
if __name__ = = "__main__" :
K = 6
computePair(K)
|
C#
using System;
class GFG{
static void computePair( double K)
{
if (K == 1)
{
Console.Write( "No" );
return ;
}
else
{
Console.Write(K * K / (K - 1) + " " );
Console.Write(K / (K - 1) + "\n" );
}
}
public static void Main(String[] args)
{
double K = 6;
computePair(K);
}
}
|
Javascript
<script>
function computePair(K)
{
if (K == 1) {
document.write( "No" );
return ;
}
else {
document.write( K * K / (K - 1) + " " );
document.write( K / (K - 1) );
}
}
var K = 6;
computePair(K);
</script>
|
Time Complexity: O(1)
Auxiliary Space; O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...