VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-compare-two-fractions/

⇱ Program to compare two fractions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to compare two fractions

Last Updated : 20 May, 2026

Given a string s containing two fractions a/b and c/d, compare them and return the greater. If they are equal, then return "equal".

Note: The string s contains "a/b, c/d"(fractions are separated by comma(,) & space( )). 

Examples :

Input: s = "5/6, 11/45"
Output: 5/6
Explanation: 5/6=0.8333 and 11/45=0.2444, So 5/6 is a greater fraction.

Input: s= "8/1, 8/1"
Output: equal
Explanation: We can see that both the fractions are same, so we'll return a string "equal".

[Naive Approach] Using Floating Point Division - O(1) Time O(1) Space

The idea is to convert both fractions into decimal values and compare them.


Output
5/6

Time Complexity: O(1)
Auxiliary Space: O(1)

[Expected Approach] Using Cross Multiplication - O(1) Time O(1) Space

The idea is to compare fractions using cross multiplication instead of division.

For two fractions a/b and c/d, compare a * dβ€…β€Šandβ€…β€Šb * c

  • If a * d > b * c, then the first fraction is greater.
  • If a * d < b * c, then the second fraction is greater.
  • Otherwise, both fractions are equal.

Output
5/6

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment