![]() |
VOOZH | about |
Given two Rational numbers, the task is to find the maximum of given two rational numbers.
Examples :
Input : first = 3/4, second= 3/2 Output : 3/2 Input : first = 100/100, second = 300/400 Output : 100/100
A simple solution is to find float values and compare the float values. The float computations may cause precision errors. We can avoid them using the below approach.
Say first = 3/2, second = 3/4
3/2
Time Complexity: O(log(max(deno,nume)))
Auxiliary Space: O(1)
An approach that works in constant time:
Let two rational number
First rational number => a / b --(i)
Second rational number => c / d --(ii)Lets assume First rational number is greater than second rational number
=> a/b > c/d --(iii)
Multiplying with (d*b) on the both side of inequality => a*d > c*b --(iv)Equation (iv) shows that if first rational number is greater than second than it will always hold the (iv) enquality.
Below is the implementation of the above approach:
3/2
Time Complexity: O(1)
Auxiliary Space: O(1)
Please suggest if someone has a better solution that is more efficient in terms of space and time.