问题描述
我有int数组,而我试图找到数组中的所有值的LCM(最小公倍数)。我已经分开写的 LCM
方法;它需要两个值作为输入,并返回最小公倍数。我的 LCM
方法工作完全正常,但是当我用它来寻找我得到一个错误的答案值的LCM。
I have an array of ints, and I'm trying to find the LCM (least common multiple) of all the values in the array. I've written an lcm
method separately; it takes two values as input, and returns the lcm. My lcm
method works perfectly fine, but when I use it to find the LCM of all the values I get a wrong answer.
下面是我的 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:
This is what I have for the lcm of the array values:
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为改编
0作为启动
和数组的长度结束
,我得到30的答案,而我想60.当我把在包含所有数字数组从1到10,我得到840而不是2520我真的无法解释。
When I put in an array that has the numbers 1 to 5 as arr
, 0 as start
and the length of the array as end
, I get 30 as the answer, while I want 60. When I put in an array containing all the numbers from 1 to 10, I get 840 instead of 2520. I really can't explain that.
该算法应该努力 - 从来就在我的脑袋算出来。想不通的问题是我的code什么。
The algorithm should work--I've worked it out in my head. Can't figure out what the problem is with my code.
任何帮助将AP preciated。
Any help will be appreciated.
推荐答案
如果你改变你的GCD功能
If you change your gcd function to
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);
}
它应该工作正常。
it should work okay.
这篇关于在Java中的数组所有号码LCM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!