# Maximum rational number (or fraction) from an array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a 2-D array that contains rational numbers (one in each row). Our task is to create a program to calculate the maximum rational number (or fraction) from an array in C++.

Problem Description − The 2-D array is of the form [n][2]. Each row has two integer values that denote the value of a and b in the equation of rational number, a/b. We need to find the greatest number out of all these rational numbers.

Let’s take an example to understand the problem,

## Input

rat[][] = {
{3, 2},
{5, 7},
{1, 9},
{11, 4}
}

## Output

11 4

## Explanation

The maximum number out of

3/2 , 5/7 , 1/9 , 11/4 is 11/4.

## Solution Approach

To solve the problem, we need to find the values of the numbers and then compare their values. But, this might give an error if the difference between the precision is greater like, if we use float we cannot differentiate between rational numbers, 34.12313431123, and 34.12313431124.

So, we will use another method to compare values. This is using the LCM of all denominators and then changing the numerators accordingly. After this, the comparison of the numerators will return the maximum number.

Program to show the implementation of our solution,

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
const int n = 4;
int findMaxRatNum(int ratNum[n][2]){
int numArray[n];
int LCM = 1;
int mavVal = 0, index = 0;
for (int i = 0; i < n; i++)
LCM = (LCM * ratNum[i][1]) / __gcd(LCM, ratNum[i][1]);
for (int i = 0; i < n; i++) {
numArray[i] = (ratNum[i][0]) * (LCM / ratNum[i][1]);
if (mavVal < numArray[i]) {
mavVal = numArray[i];
index = i;
}
}
return index;
}
int main(){
int ratNum[n][2] = {{3, 2},{5, 7},{1, 9},{11, 4}};
int i = findMaxRatNum(ratNum);
cout<<"The maximum rational number from an array is "<<ratNum[i][0]<<"/"<<ratNum[i][1];
}

## Output

The maximum rational number from an array is 11/4
Published on 03-Jul-2020 11:26:32