在 C++ 中求有理数的 LCM


接下来,我们将了解如何求有理数的 LCM。我们有一个有理数列表。假设列表如下所示:{2/7, 3/14, 5/3},则 LCM 为 30/1。

为了解决这个问题,我们必须计算所有分子的 LCM,然后计算所有分母的 GCD,然后有理数的 LCM 等于−

$$LCM =\frac{所有分子的LCM}{所有分母的GCD}$$

示例

 在线演示

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int LCM(int a, int b) {
   return (a * b) / (__gcd(a, b));
}
int numeratorLCM(vector<pair<int, int> > vect) {
   int result = vect[0].first;
   for (int i = 1; i < vect.size(); i++)
      result = LCM(vect[i].first, result);
   return result;
}
int denominatorGCD(vector<pair<int, int> >vect) {
   int res = vect[0].second;
   for (int i = 1; i < vect.size(); i++)
      res = __gcd(vect[i].second, res);
   return res;
}
void rationalLCM(vector<pair<int, int> > vect) {
   cout << numeratorLCM(vect) << "/"<< denominatorGCD(vect);
}
int main() {
   vector<pair<int, int> > vect;
   vect.push_back(make_pair(2, 7));
   vect.push_back(make_pair(3, 14));
   vect.push_back(make_pair(5, 3));
   cout << "LCM of rational numbers: "; rationalLCM(vect);
}

输出

LCM of rational numbers: 30/1

更新日期:2019 年 10 月 21 日

121 次查看

开启你的 事业

完成课程以获得认证

开始
广告
© . All rights reserved.