java - Java中数组中所有数字的最小公倍数(LCM)

标签 java arrays recursion lcm

我有一个整数数组,我试图找到数组中所有值的 LCM(最小公倍数)。我单独写了一个lcm方法;它接受两个值作为输入,并返回 lcm。我的 lcm 方法工作得很好,但是当我用它来查找所有值的 LCM 时,我得到了错误的答案。

这是我的 gcdlcm 方法:

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/

相关文章:

c - 动态创建一个只有一个已知维度的二维数组

python - 可以用递归完成吗?

java - 为什么jetty服务器在发送请求时不同意协议(protocol)?

java - Neo4j 中的索引

Java 传递参数数组

在 C 中更改 char[]

algorithm - 如何在递归调用中获取路径

java - 偶数长度字符串的字符串越界错误

java - 如何添加自定义 Java 命令行选项?

java - tomcat 在 html 中显示 404 错误,但 jsp 工作正常