You’re given two fractions, a/b, and c/d. Your task is to add these two fractions and print this answer in the simplest form.
The first line contains an integer 'T', denoting the number of test cases.
The first line of each test case contains four space-separated integers 'a', 'b', 'c', and 'd', as described in the problem statement.
Output Format :
For each test case, print two space-separated integers 'x' and 'y', where the sum (a/b)+(c/d) = x/y in the simplest form.
Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10 ^ 4
1 <= a,b,c,d <= 10 ^ 9
Time Limit: 1 sec
Where 'T' denotes the number of test cases, 'a', 'b', 'c' and 'd' denote the integers given as input in the problem.
1
5 7 4 9
73 63
Sum of 5/7 + 4/9 = 73/63, which is already in its simplest form because we cannot reduce it further.
1
1 500 2 1500
1 300
Sum of 1/500 + 2/1500 = 5/1500, which after reducing in simplest form becomes 1/300.
Basic Mathematics
As it is difficult to add fractions with different denominators, we first make them equal and follow the following steps to reach our answer in the simplest form.
O(log(min(b,d)), where b and d are the denominators of the given two fractions.
This is the time used to calculate the LCM of two numbers using the Euclidean Algorithm. This comes from Fibonacci Numbers. If we observe carefully we can notice a pattern in the steps used for calculating the GCD of two numbers, for the nth step the numbers would be (fib(n), fib(n+1)). Now Fibonacci series is an exponentially growing series where the ratio of nth/(n-1)th term approaches (sqrt(5)-1)/2 which is also called the golden ratio. So we can see that the time complexity of the algorithm increases linearly as the terms grow exponentially hence the time complexity would be log(min(a,b)).
O(1).
Constant space is being used. Hence, the overall space complexity is O(1).