views:

186

answers:

6

Hi I have written this code: but it will show this error for this line : obj.function(600851475143);

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();
    }
}

please help me! thanks

+6  A: 

You need to use a long literal:

obj.function(600851475143l);  // note the "l" at the end

But I would expect that function to run out of memory (or time) ...

Thilo
it is considered a better practice to make the `l` upper-case, so that it is easily distinguishable from `1`
Bozho
@Bozho: Agreed. But I have a Perl background. I code "write-only" :-)
Thilo
-1 for using lowercase l.
starblue
+7  A: 

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

Yuliy
+7  A: 

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.

Roman
No need to change the number, though...
Thilo
@Thilo: He might be not good in memorising numbers and also lazy in copy pasting things. :)
Adeel Ansari
+3  A: 

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).

Andre Holzner
+4  A: 

The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.

To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.

Since some Fonts make it hard to distinguish "1" and lower case "l" from each other you should always use the upper case "L".

josefx
+1  A: 

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.

JVM