Ani*_*uha 2 java arrays recursion lcm
我有一个int数组,我正在尝试找到数组中所有值的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));
}
Run Code Online (Sandbox Code Playgroud)
这就是我对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)));
}
Run Code Online (Sandbox Code Playgroud)
当我输入一个数字为1到5 的数组arr
,0 start
和数组的长度为时end
,我得到30作为答案,而我想要60.当我输入一个包含从1到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);
}
Run Code Online (Sandbox Code Playgroud)
它应该工作正常.