Project Euler #3 out of integer range java [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-04 06:04:12

问题


The code is supposed to give back the biggest prime number. More about the task here: https://projecteuler.net/problem=3

int checkFactors(double na) {

        long n = (long) na;
        int biggestPrimeFactor = 0;
        for (int i = 1; i < n; i++)
            if (n % i == 0 && isPrimFaktor(i) && i > biggestPrimeFactor)
                biggestPrimeFactor = i;

        return biggestPrimeFactor;
    }

boolean isPrimeFactor(int n) {

        int length= 0;
        for (int i = n; i > 0; i--)
            if (n % i == 0)
                length++;

        if (length== 2)
            return true;
        return false;
    }

I decided to make the parameter of checkFactors() a double because I tried to test why my code didn't work properly.

System.out.println(checkFactors(13195));

works and returns "29".

However, System.out.println(checkFactors(600851475143)); does not work,

"600851475143 of type int is out of range".

System.out.println(checkFactors(600851475143.0));

does compile but gives me after a couple of seconds an ArithmeticException.


回答1:


600851475143 of type int is out of range

  • This number is bigger than int can store. Appending .0 to the number converts the number into a double which can represent that number
  • Instead of .0 you can do checkFactors(600851475143d) which ensure the number is a double and not an int



回答2:


Use long as a data type for na and also biggestPrimeFactor. The values are too large for storing in an int variable.




回答3:


Try to make Your parameter back to long and make letter L after your large number like this 600851475143L, I think it will work



来源:https://stackoverflow.com/questions/27923619/project-euler-3-out-of-integer-range-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!