作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个整数数组,我试图找到数组中所有值的 LCM(最小公倍数)。我单独写了一个lcm
方法;它接受两个值作为输入,并返回 lcm。我的 lcm
方法工作得很好,但是当我用它来查找所有值的 LCM 时,我得到了错误的答案。
这是我的 gcd
和 lcm
方法:
public static int gcd(int a, int b){
if (a<b) return gcd(b,a);
if (a%b==0) return b;
else return gcd(a, a%b);
}
public static int lcm(int a, int b){
return ((a*b)/gcd(a,b));
}
这是我的数组值的 lcm:
public static int lcmofarray(int[] arr, int start, int end){
if ((end-start)==1) return lcm(arr[start],arr[end-1]);
else return (lcm (arr[start], lcmofarray(arr, start+1, end)));
}
当我放入一个数组时,其中数字 1 到 5 作为 arr
,0 作为 start
,数组的长度作为 end
>,我得到 30 作为答案,而我想要 60。当我放入包含从 1 到 10 的所有数字的数组时,我得到 840 而不是 2520。我真的无法解释这一点。
这个算法应该可以工作——我已经在脑子里计算出来了。无法弄清楚我的代码有什么问题。
任何帮助将不胜感激。
最佳答案
如果您将 gcd 函数更改为
public static int gcd(int a, int b){
if (a<b) return gcd(b,a);
if (a%b==0) return b;
else return gcd(b, a%b);
}
应该可以正常工作。
关于java - Java中数组中所有数字的最小公倍数(LCM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689529/
我是一名优秀的程序员,十分优秀!