Given a fraction in form of a/b where a & b are positive integers. Find ?X such that when it is added to numerator as well as denominator of given fraction it will result into a new Ir-reducible fraction c/d.
Examples:
Input : a = 4, b = 10, c = 1, d = 2
Output : ?X = 2
Explanation : (a + ?X)/(b + ?X) =
(4 + 2) / (10 + 2) = 6/12 = 1/2 = c/d
Input : a = 4, b = 10, c = 2, d = 5
Output : ?X = 0
Explanation : (a + ?X) / (b + ?X) =
(4) / (10) = 2 / 5 = c/d
To solve this type of problem rather than implementing just a programming approach we have to do a little of mathematics. mathematics just necessary is as:
As per question we have to find ?X such that:
=> (a + ?X) / (b + ?X) = c / d
=> ad + d?X = bc + c?X
=> d?X - c?X = bc - ad
=> ?X (d - c) = bc -ad
=> ?X = (bc - ad) / (d - c)
So, in a way to finding ?X we have to only calculate
.
C++
#include <bits/stdc++.h>
using namespace std;
int findDelta( int a, int b, int c, int d)
{
return (b * c - a * d) / (d - c);
}
int main()
{
int a = 3, b = 9, c = 3, d = 5;
cout << "\u0394X = " << findDelta(a, b, c, d);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int findDelta( int a, int b,
int c, int d)
{
return (b * c - a *
d) / (d - c);
}
public static void main(String args[])
{
int a = 3 , b = 9 ,
c = 3 , d = 5 ;
System.out.print( "\u0394X = " +
findDelta(a, b, c, d));
}
}
|
Python3
def findDelta(a, b, c, d) :
return int ((b * c -
a * d) /
(d - c));
a = 3 ; b = 9 ;
c = 3 ; d = 5 ;
print ( "X = {}" .
format (findDelta(a, b,
c, d)));
|
C#
using System;
class GFG
{
static int findDelta( int a, int b,
int c, int d)
{
return (b * c - a *
d) / (d - c);
}
static void Main()
{
int a = 3, b = 9,
c = 3, d = 5;
Console.Write( "\u0394X = " +
findDelta(a, b, c, d));
}
}
|
PHP
<?php
function findDelta( $a , $b ,
$c , $d )
{
return ( $b * $c -
$a * $d ) / ( $d - $c );
}
$a = 3; $b = 9;
$c = 3; $d = 5;
echo "?X = " .findDelta( $a , $b ,
$c , $d );
?>
|
Javascript
<script>
function findDelta(a, b, c, d)
{
return (b * c - a *
d) / (d - c);
}
let a = 3, b = 9,
c = 3, d = 5;
document.write( "\u0394X = " +
findDelta(a, b, c, d));
</script>
|
Output:
?X = 6
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Feb, 2023
Like Article
Save Article