gpt4 book ai didi

java - 如何在一组数字上找到 GCD、LCM

转载 作者:IT老高 更新时间:2023-10-28 13:53:19 25 4
gpt4 key购买 nike

在一组数字上计算最大公约数和最小公倍数的最简单方法是什么?可以使用哪些数学函数来查找此信息?

最佳答案

我用过Euclid's algorithm求两个数的最大公约数;可以通过迭代得到更大数字集的 GCD。

private static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}

private static long gcd(long[] input)
{
long result = input[0];
for(int i = 1; i < input.length; i++) result = gcd(result, input[i]);
return result;
}

最小公倍数有点棘手,但最好的方法可能是reduction by the GCD ,可以类似地迭代:

private static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}

private static long lcm(long[] input)
{
long result = input[0];
for(int i = 1; i < input.length; i++) result = lcm(result, input[i]);
return result;
}

关于java - 如何在一组数字上找到 GCD、LCM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com