Find LCM of rational numbers

Given an array of rational numbers, the task is to find the LCM of these numbers.


Input : vect[] = {2/7, 3/14, 5/3}
Output : 30/1

Input : vect[] = {3/14, 5/3}
Output : 15/1

Input : vect[] = {3/4, 3/2}
Output : 3/2

First find the lcm of all numerator of rational number then find the gcd of all the denominator of rational number then divide lcm of all numerator/ gcd of all the denominator this the lcm of rational number’s.


      LCM of all the numerator of Rational number's
lcm = -----------------------------------------------
      GCD of all the denominator of Rational number's




// CPP program to find LCM of given array
#include <bits/stdc++.h>
using namespace std;
// get lcm of two numbers
int LCM(int a, int b)
    return (a * b) / (__gcd(a, b));
// Finds LCM of numerators
int lcmOfNumerator(vector<pair<int, int> > vect)
    // calculate the lcm of all numerators
    int lcm = vect[0].first;
    for (int i = 1; i < vect.size(); i++) 
        lcm = LCM(vect[i].first, lcm); 
    // return all numerator lcm
    return lcm;
// Get GCD of all the denominators
int gcdOfDemoninators(vector<pair<int, int> > vect)
    // calculate the gcd of all the denominators
    int gcd = vect[0].second;
    for (int i = 1; i < vect.size(); i++) 
        gcd = __gcd(vect[i].second, gcd); 
    // return all denominator gcd
    return gcd;
// find lcm of all the rational number
void lcmOfRationals(vector<pair<int, int> > vect)
    // return the LCM of all numerator/ GCD of all 
    // denominator
    cout << lcmOfNumerator(vect) << "/"
        << gcdOfDemoninators(vect);
// Driver code
int main()
    vector<pair<int, int> > vect;
    // give rational number 2/7, 3/14, 5/3
    // make pair as a numerator and denominator
    vect.push_back(make_pair(2, 7));
    vect.push_back(make_pair(3, 14));
    vect.push_back(make_pair(5, 3));
    return 0;




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.