Java中数组中所有数字的LCM

我有一个整数数组,我试图找到该数组中所有值的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作为开始并且以数组的长度作为结束的数组时,我得到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);
}

它应该工作正常.

上一篇:c – 计算模数为1000000007的N个数的LCM


下一篇:Orac and LCM CodeForces - 1349A