Java中数组中所有数字的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)); }
这就是我对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.我实在无法解释。
该算法应该工作 – 我已经在脑海中解决了这个问题。 无法弄清楚我的代码有什么问题。
任何帮助将不胜感激。
如果您将gcdfunction更改为
public static int gcd(int a, int b){ if (a
它应该工作正常。
上面的方法看起来不错,但由于递归调用它会出现堆栈溢出错误:
请找到以下解决方案:
public int findHCF(int a, int b) { if (b>a){ return findHCF(b, a); } while(a%b!=0){ int temp = b; b=a%b; a=temp; } return b; }