Given four integers a, b, c and d. The task is to find the number X which when added to the numbers a and b the ratio changes from a : b to c : d.
Examples:
Input: a = 3, b = 6, c = 3, d = 4
Output: 6
When 6 is added to a and b
a = 3 + 6 = 9
b = 6 + 6 = 12
And, the new ratio will be 9 : 12 = 3 : 4
Input: a = 2, b = 3, c = 4, d = 5
Output: 2
Approach: Old ratio is a : b and new ratio is c : d. Let the required number be X,
So, (a + X) / (b + X) = c / d
or, ad + dx = bc + cx
or, x(d – c) = bc – ad
So, x = (bc – ad) / (d – c)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getX( int a, int b, int c, int d)
{
int X = (b * c - a * d) / (d - c);
return X;
}
int main()
{
int a = 2, b = 3, c = 4, d = 5;
cout << getX(a, b, c, d);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getX( int a, int b, int c, int d)
{
int X = (b * c - a * d) / (d - c);
return X;
}
public static void main (String[] args)
{
int a = 2 , b = 3 , c = 4 , d = 5 ;
System.out.println (getX(a, b, c, d));
}
}
|
Python
def getX(a, b, c, d):
X = (b * c - a * d) / / (d - c)
return X
a = 2
b = 3
c = 4
d = 5
print (getX(a, b, c, d))
|
C#
using System;
class GFG
{
static int getX( int a, int b, int c, int d)
{
int X = (b * c - a * d) / (d - c);
return X;
}
static public void Main ()
{
int a = 2, b = 3, c = 4, d = 5;
Console.Write(getX(a, b, c, d));
}
}
|
Javascript
<script>
function getX(a , b , c , d)
{
var X = (b * c - a * d) / (d - c);
return X;
}
var a = 2, b = 3, c = 4, d = 5;
document.write(getX(a, b, c, d));
</script>
|
Time Complexity: O(1), since there is a basic arithmetic operation that takes constant time.
Auxiliary Space: O(1), since no extra space has been taken.