Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long Division in Java not working as expected

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?

like image 962
Aakash Goel Avatar asked Jul 20 '11 17:07

Aakash Goel


People also ask

How do you divide a long number in Java?

Java Long divideUnsigned() Method. The divideUnsigned() method of Java Long class is used to return the unsigned quotient by dividing the first argument with the second argument such that each argument and the result is treated as an unsigned argument.

Does Java automatically do integer division?

Java does integer division, which basically is the same as regular real division, but you throw away the remainder (or fraction). Thus, 7 / 3 is 2 with a remainder of 1. Throw away the remainder, and the result is 2. Integer division can come in very handy.

Does Java do floor division by default?

Is there any way to do floor division in Java? Note, though, (if you've been using python3. x) that in Java, dividing two integers will always use floor division.


2 Answers

The long x you are creating isn't the value you expected. It is in the integer range. To create longs, use:

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` */
like image 168
Martijn Courteaux Avatar answered Sep 19 '22 19:09

Martijn Courteaux


The expressions 24*60*60*1000*1000 is an int type not a long What you want is 24L*60*60*1000*1000 which is long

This is what you have.

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

what you want is

final long x = 24L*60*60*1000*1000;
final long y = 24L*60*60*1000;
System.out.println(x/y);
like image 33
Peter Lawrey Avatar answered Sep 18 '22 19:09

Peter Lawrey