VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-max-two-rational-numbers/

⇱ Find max of two Rational numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find max of two Rational numbers

Last Updated : 24 Jan, 2023

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 

  • First take a LCM of (4, 2) which is denominator of rational number. so the LCM of this is 4, then divide with both denominator and multiple with numerator of first and second respectively so the denominator value is first numerator = 6, second numerator = 3.
  • Then find the max between these two. so here first numerator is max then print first rational number.

Output
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:


Output
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.
 

Comment