Monday 16 January 2012

Long division in java (for large numbers)

class LongDiv{
public static void main(String [] args){

    final long x = 24*60*60*1000*1000;
    final long y = 24*60*60*1000;
    System.out.println(x/y);
}
}


although the expected answer is 1000, but the javac gives it as 5. Reason?

Solution:
This happens because / is int operator, so large values while division are converted to integer and overflow happens. So to stop this "silent overflow" we have to use literal L to stop it.
final long x = 24L*60L*60L*1000L*1000L;
final long y = 24L*60L*60L*1000L;
System.out.println(x/y);



The x you computed, in the integer range, was 500654080. This divided by the y ( = 86400000), results in 5.794607407407407.... Java truncates the decimal part which causes the 5.

By adding an L after the number literal, you tell the compiler to compile it as a long instead of an int. The value for x you expected is 86400000000. But is was compiled as an int.

We can reproduce the wrong value for x (500654080) by truncating it to an int:
// First correct
long x = 24L*60L*60L*1000L*1000L;
/* x = `86400000000`; */
// Now truncate
x &= 0xFFFFFFFFL; // again: don't forget the L suffix
/* x = `500654080` */

Some languages don't do this, but support target typing, a language feature wherein the type of the variable in which a result is to be stored influences the type of the computation.

No comments:

Post a Comment