gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:01:23 25 4
gpt4 key购买 nike

我有一个整数数组,我试图找到数组中所有值的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com