user1390463
user1390463

Reputation: 83

Java mistaking primitive data types?

Problem: I can't store the number '600851475143'. I realize this number is bigger than what an int can hold and is smaller than the maximum long value. However, my program isn't registering the variable "number" as a long, it is registering it as a int. Can someone shed some light onto this problem?

** - Line of the problem

public class Problem3{
//What is the largest prime factor of the number 600851475143
public static void main(String[] args){
  ***long number = 600851475143 , total = 0;
    for(long x = (number-1)/2; x>1; x--)
      if(number%x == 0 && isPrime(x)) total += x;
    System.out.println(total);
}
private static boolean isPrime(long determine){
  for(long x = determine/2 - 1; x>1; x--)
    if(determine%x ==0) return false;
  return true;
}

}

SOLUTION: As Jim said below, in order to of type long, one has to put a "L" or "l" at the end of the number. "An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1." - From Oracle site on Primitive types.

A little more info: Java's L number (long) specification

Upvotes: 1

Views: 668

Answers (3)

Jim Garrison
Jim Garrison

Reputation: 86774

Long literals need to be expressed with a trailing "L", as in 600851475143L

Upvotes: 12

user207421
user207421

Reputation: 310884

"my program isn't registering the variable "number" as a long, it is registering it as a int".

That's not correct. You declared it as a long. It's a long.

What you must be getting is something quite different: a compile error on the constant 600851475143. Try 600851475143L. I suggest that if you read the compiler error message more carefully you would have seen that.

Upvotes: 4

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

Put a small 'L' in this literal value:

 600851475143L

The reason is:

An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

You can use this notation too, to be more clear:

 600_851_475_143L

Upvotes: 4

Related Questions