“Integer number too large” error message for 60085

2019-01-02 16:02发布

public class Three {
    public static void main(String[] args) {
        Three obj = new Three();
        obj.function(600851475143);
    }

    private Long function(long  i) {
        Stack<Long> stack = new Stack<Long>();

        for (long j = 2; j <= i; j++) {
            if (i % j == 0) {
                stack.push(j);
            }
        }
        return stack.pop();
    }
}

When the code above is run, it produces an error on the line obj.function(600851475143);. Why?

标签: java integer
8条回答
梦寄多情
2楼-- · 2019-01-02 16:07

You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).

This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).

查看更多
无色无味的生活
3楼-- · 2019-01-02 16:07

Apart from all the other answers, what you can do is :

long l = Long.parseLong("600851475143");

for example :

obj.function(Long.parseLong("600851475143"));
查看更多
低头抚发
4楼-- · 2019-01-02 16:10

Append suffix L: 23423429L.

By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values.

查看更多
有味是清欢
5楼-- · 2019-01-02 16:13

At compile time the number "600851475143" is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.

查看更多
长期被迫恋爱
6楼-- · 2019-01-02 16:16

Or, you can declare input number as long, and then let it do the code tango :D ...

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter a number");
    long n = in.nextLong();

    for (long i = 2; i <= n; i++) {
        while (n % i == 0) {
            System.out.print(", " + i);
            n /= i;
        }
    }
}
查看更多
看风景的人
7楼-- · 2019-01-02 16:19

600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an "L": 600851475143L

查看更多
登录 后发表回答