# Find max of two Rational numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two Rational Numbers. Our task is to find max of two Rational numbers.

Here, the rational numbers are in the form of p/q.

Let’s take an example to understand the problem,

Input: rat1 = 5/4, rat2 = 3/2

Output: 3/2

Explanation:

5/4 = 1.25
3/2 = 1.5

## Solution Approach −

A simple solution to the problem is by using a method similar to the one we used to perform in school.

For this, we will find the L.C.M of the denominator. And then multiply the numerator based on the denominators value. Then for the common denominator, the rational number with maximum numerator value is the max one.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int findLCM(int a, int b) {

return (a * b) / (__gcd(a, b));
}

void maxRational(int ratOneNum, int ratOneDen, int ratTwoNum, int ratTwoDen) {

int k = findLCM(ratOneDen, ratTwoDen);

int oneNum = ratOneNum * k / (ratOneDen);
int twoNum = ratTwoNum * k / (ratTwoDen);

if(oneNum > twoNum)
cout<<ratOneNum<<"/"<<ratOneDen;
else
cout<<ratTwoNum<<"/"<<ratTwoDen;

}

int main() {

int ratOneNum = 5;
int ratOneDen = 4;
int ratTwoNum = 3;
int ratTwoDen = 2;
cout<<"The maximum of the two rational Numbers is ";
maxRational(ratOneNum, ratOneDen, ratTwoNum, ratTwoDen);
return 0;
}

## Output

The maximum of the two rational Numbers is 3/2

Published on 25-Jan-2021 05:12:19