Search code examples
javatypesprimitive

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


Solution

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