是否有 C++ 算法来计算多个数字的最小公倍数,例如 lcm(3,6,12)
或 lcm(5,7,9,12)
?
最佳答案
您可以使用 std::accumulate 和一些辅助函数:
#include <iostream>
#include <numeric>
int gcd(int a, int b)
{
for (;;)
{
if (a == 0) return b;
b %= a;
if (b == 0) return a;
a %= b;
}
}
int lcm(int a, int b)
{
int temp = gcd(a, b);
return temp ? (a / temp * b) : 0;
}
int main()
{
int arr[] = { 5, 7, 9, 12 };
int result = std::accumulate(arr, arr + 4, 1, lcm);
std::cout << result << '\n';
}
关于C++算法计算多个数字的最小公倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4229870/