在一组数字上计算最大公除数和最小公倍数的最简单方法是什么?哪些数学函数可用于查找此信息?
我已经使用Euclid算法找到了两个数字的最大公约数。可以迭代以获得更大数量的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;
}
最小公倍数有些棘手,但最好的方法可能是通过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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句