在 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
廣告