Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的Euler项目5,为什么会有不同的结果?_Java_Algorithm - Fatal编程技术网

java中的Euler项目5,为什么会有不同的结果?

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

我认为答案倍数(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
 *  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)