-1

所以出于某种原因,这给了我除以 0 错误,有什么想法吗?

package euler;
public class LargePrimeFactor {
    public static long max = 600851475143L;

    public static int isPrime() {
        int count = 0;
        for(int i = 1; i < max; i++) {
            if(max % i == 0)count += i;
        }
        return count;
    }

     public static void main(String[] args) {
        System.out.println(max/isPrime());

    }
 }
4

2 回答 2

0

您会收到此错误,因为的值ioverflow在. Your是一种持有价值(大于 Integer.MAX_VALUE)但为 int 的类型。所以在某个时间点,最终会到达由于和=会抛出错误。为了解决这个问题,我建议将类型设为 long。Integer.MAX_VALUEInteger overflowmaxlong600851475143Lii0overflowmax % i600851475143L/0i

   long count = 0;
   for(long i = 1; i < max; i++) {
        if(max % i == 0)count += i;
    }
于 2019-03-03T17:30:44.670 回答
0

变量i的类型为int的最大值int(2^31) - 1 = 2147483647。当最大值加int一时,它会溢出,成为最小的 int 值 ( -2^31 = -2147483648)。这称为环算术继续给这个变量加 1,它最终会变成0,从而产生一个DivisionByZeroException(记住,除法和模数在语义上是耦合的)。

顺便说一句:通过同样的推理,您可以看到这i < max将永远是正确的。

于 2019-03-03T17:36:49.023 回答