java中的Euler项目5,为什么会有不同的结果?
我认为答案倍数(1,19)和倍数(1,20)会得到相同的结果。但就我的代码而言,它们是不同的,multiple(1,19)=232792560(正确答案)和multiple(1,20)=18044195这是错误答案!!!我知道还有很多更简单的算法,但我只想知道我的问题在哪里。。。java中的Euler项目5,为什么会有不同的结果?,java,algorithm,Java,Algorithm,我认为答案倍数(1,19)和倍数(1,20)会得到相同的结果。但就我的代码而言,它们是不同的,multiple(1,19)=232792560(正确答案)和multiple(1,20)=18044195这是错误答案!!!我知道还有很多更简单的算法,但我只想知道我的问题在哪里。。。 谁能告诉我这个问题?您在计算时有int溢出 /* Smallest multiple */ /* * 2520 is the smallest number that can be divided by each
谁能告诉我这个问题?您在计算时有
int
溢出
/* Smallest multiple */
/*
* 2520 is the smallest number that can be divided by each
* of the numbers from 1 to 10 without any remainder.What
* is the smallest positive number that is evenly divisible
* by all of the numbers from 1 to 20?
*/
public class SmallestMultiple {
public static int gcd(int m, int n){
if(n>m){
int temp = m;
m = n;
n = temp;
}
int gcdNum = m;
while(m != 0){
m = gcdNum%n;
gcdNum = n;
n = m;
}
return gcdNum;
}
private static int lcm(int m, int n){
return m*n/gcd(m,n);
}
static int multiple(int start, int end){
if(start > end){
int temp = end;
end = start;
start = temp;
}
else if(start == end)
return start;
else
return lcm(end, multiple(start, end-1));
return multiple(start, end);
}
public static void main(String[] args) {
System.out.println(multiple(11,19)); // line a--Which is equal to multiple(1,19)
System.out.println(multiple(11,20)); // line b--Which is equal to multiple(1,20)
}
}
因此,您可以获得360883904/20=18044195
你可以
- 使用
或long
- 计算
m*(n/gcd(n,m))
为了避免溢出(第二种方法不会让您走得更远,如果上限为23,
int
太小,无法容纳结果)。您的问题几乎就是一个整数溢出
Java中最大的int
数字是Integer.MAX\u VALUE=2147483647
在某些时候,您尝试运行lcm(202327272560)
。后者是multiplay(1,19)
的结果
在函数内部,您尝试计算m*n/gcd(m,n)
使用m==20
,n==18044195
和gcd(m,n)==20
,这将得到20*18044195/20
第一个乘积实际上是20*18044195==4655851200
,它大于Integer.MAX_VALUE
,因此会发生溢出,并且您的总结果会变差
一种解决方案是在任何地方切换到
long
类型,其最大值为long.MAX_value==9223372036854775807
非常感谢,我已经从您的答案中找到了原因!再次感谢!!!因为我是stackoverflow的新手,所以我不能为其他人投票(声誉低于15-。-!!!),很遗憾~@mitcc你不能投票,但你可以接受答案,这样问题就解决了。
Prelude> 232792560 * 20
4655851200
Prelude> it `quotRem` (2^32)
(1,360883904)