I have been asked a question in Interview which was related to Integer overflow. The question was simple but I could not find a an easy solution to count the result of overflowed value.
For Example, Following program should print 1000 as output but it prints 5 due the Integer overflow.
public class IntegerOvewflow {
/**
* Java does not have 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.
*
* #param args
*/
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
But, here can we use any specific formula or equation to calculate the output of overflowed value. Here the number is really big and not easy to judge the output quickly by human mind.
Specify that they are long with L, because if not you're doing int multiplication which results in an int which touch the overflow and then store into a long
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000L;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); // 1000
}
Check out : https://ideone.com/5vHjnH
This is the classic Problem from the very good book , Java Puzzlers Link to Book
Puzzle 3: Long Division
This puzzle is called Long Division because it concerns a program that divides
two long values. The dividend represents the number of microseconds in a day;
the divisor, the number of milliseconds in a day. What does the program print?
public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
Solution 3: Long Division
This puzzle seems reasonably straightforward. The number of milliseconds per
day and the number of microseconds per day are constants.
For clarity, they are expressed as products.
The number of microseconds per day is (24 hours/day · 60
minutes/hour · 60 seconds/minute · 1,000 milliseconds/second · 1,000 microseconds/millisecond).
The number of milliseconds per day differs only in that it is
missing the final factor of 1,000. When you divide the number of microseconds
per day by the number of milliseconds per day, all the factors in the divisor cancel
out, and you are left with 1,000, which is the number of microseconds per millisecond. Both the divisor and the dividend are of type long, which is easily large
enough to hold either product without overflow.
It seems, then, that the program
must print 1000. Unfortunately, it prints 5. What exactly is going on here?
The problem is that the computation of the constant MICROS_PER_DAY does
overflow. Although the result of the computation fits in a long with room to spare,
it doesn’t fit in an int. The computation is performed entirely in int arithmetic,
and only after the computation completes is the result promoted to a long. By
then, it’s too late: The computation has already overflowed, returning a value that
is too low by a factor of 200. The promotion from int to long is a widening primitive conversion [JLS 5.1.2], which preserves the (incorrect) numerical value. This
value is then divided by MILLIS_PER_DAY, which was computed correctly because
it does fit in an int. The result of this division is 5.
So why is the computation performed in int arithmetic? Because all the factors that are multiplied together are int values. When you multiply two int values, you get another int value. Java does not have 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.
It’s easy to fix the program by using a long literal in place of an int as the
first factor in each product. This forces all subsequent computations in the expression to be done with long arithmetic. Although it is necessary to do this only in
the expression for MICROS_PER_DAY, it is good form to do it in both products. Similarly, it isn’t always necessary to use a long as the first value in a product, but it is good form to do so. Beginning both computations with long values makes it clear that they won’t overflow.
This program prints 1000 as expected:
public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
The lesson is simple: When working with large numbers, watch out for
overflow—it’s a silent killer. Just because a variable is large enough to hold a
result doesn’t mean that the computation leading to the result is of the correct
type. When in doubt, perform the entire computation using long arithmetic.
The lesson for language designers is that it may be worth reducing the likelihood of silent overflow. This could be done by providing support for arithmetic
that does not overflow silently. Programs could throw an exception instead of
overflowing, as does Ada, or they could switch to a larger internal representation
automatically as required to avoid overflow, as does Lisp. Both of these
approaches may have performance penalties associated with them. Another way
to reduce the likelihood of silent overflow is to support target typing, but this adds
significant complexity to the type system [Modula-3 1.4.8].
You can use BigInteger class for exactly these purposes.
Oracle documentation: here
There is a good quick article in this link
Related
why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?
Because the multiplication overflows 32 bit integers. In 64 bits it's okay:
public class Test
{
public static void main(String[] args)
{
int intProduct = 24 * 60 * 60 * 1000 * 1000;
long longProduct = 24L * 60 * 60 * 1000 * 1000;
System.out.println(intProduct); // Prints 500654080
System.out.println(longProduct); // Prints 86400000000
}
}
Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.
You need to start with 24L * 60 * ... because the int overflows.
Your question BTW is a copy/paste of Puzzle 3: Long Division from Java Puzzlers ;)
If you want to perform that calculation, then you must either re-order the operations (to avoid overflow) or use a larger datatype. The real problem is that arithmetic on fixed-size integers in Java is not associative; it's a pain, but there's the trade-off.
I want to get the number of micro seconds in a day
so I tried as per below
long microDay = 24 * 60 * 60 * 1000 * 1000;
for which I am expecting value as 86400000000 but when I print it
System.out.println(microDay);
The value is 500654080
After spending 3 hours and breaking my head to know the reason,final I found that java think 24,60 and 1000 as int values and int*int =int but the maximum value of int is 2147483647 so it cant store 86400000000 and hence it the output is 500654080 (but I am not sure)
In the second case I wanted to calculate miliseconds in a day and the formula goes like this
long miliDay = 24 * 60 * 60 * 1000;
System.out.println(miliDay );
output 86400000
now when I did
System.out.println(microDay/ miliDay);
output 5
but when I tried this in a calculator 500654080/86400000= 5.794607407407407
why there is different in result?
You're performing 32-bit integer arithmetic, as every operand in 24 * 60 * 60 * 1000 * 1000 is an int... but the result is bigger than Integer.MAX_VALUE, so it's overflowing (just as you suspected). (This is actually happening at compile-time in this case, because it's a compile-time constant, but the effect is the same as if it happened at execution time.)
Effectively, each operation is truncated to 32 bits. As it happens, only the final multiplication by 1000 takes the result over 231 - 86400000 is fine.
86400000000 in binary is:
1010000011101110101110110000000000000
^
\- Bit 33
So after overflow, we just chop any leading bits until we've got 32:
00011101110101110110000000000000
And that value is 500654080.
Just use long instead, e.g.
long microDay = 24L * 60L * 60L * 1000L * 1000L;
(You definitely don't need all those constants to be of type long, but being consistent means it's obvious that all the operations will be performed using 64-bit arithmetic, with no need to consider associativity etc.)
A better approach, however, would be to use TimeUnit:
long microDay = TimeUnit.DAYS.toMicroseconds(1);
As for the division part, you're performing integer division - so the result is the integer part, rounded towards 0. If you want floating point arithmetic, you need to cast one of the operands to float or double... although if you start off with the right values, of course, you should get an exact integer anyway (1000).
For the first part, put a "L" at the end of one (or more) of the constants and Java will then use long arithmetic. e.g.
long microDay = 24L * 60 * 60 * 1000 * 1000;
Addendum: Why did you get 500654080?
86400000000 decimal = 141DD76000 hex.
But, the integer only holds 32 bits, which is 8 "digits". So you lose the leading 14 and retain 1DD76000 hex.
Converting that to decimal gives 500654080.
As for the division, when you divide ints by ints (or longs by longs) Java returns the result as an int or long, so it has to truncate (or round, but Java chose to truncate) the result to 5 instead of 5.7946... Force it to do floating point arithmetic by casting one of the values to a double, e.g.
System.out.println((double)microDay/ miliDay);
When you are performing a division between 2 integers, the results are an integer. The results of the arithmetic operation will be rounded down to the nearest integer.
int i = 5 / 2; // 2.5 is rounded down to 2
if you want the output to include the decimal precision, you will need to use a different primitive data type and explicitly specify your operands to be doubles.
double j = 5 / 2; //2.0 as 5 / 2 yields and integer 2 which will be casted to a double
double j = 5 / 2.0; //2.5 explicit usage of a double will tell the compiler to return the results in double
The nuclear operations inside
long microDay = 24 * 60 * 60 * 1000 * 1000;
are all Integers specific. Max value of Integer object is 2147483647. Which exceeds the original output which is long.
Simply specifying long to variable doesn't mean all operations using [ * ] will be done using long instances. All operations done in assignment became sort of truncated.
Solution is to explicitly specify that all nuclear operations should happen over long instance and not int instances.
long microDay = 24L * 60L * 60L * 1000L * 1000L;
I'm really puzzled by this. I'm dividing two positive numbers and getting a negative result (I'm using Java).
long hour = 92233720368L / (3600 * 1000000 );
I got as result -132.
But if I divide them as two long numbers, I get the right result:
long hour1 = 92233720368L / (3600000000L );
Then I get as result: 25
I'm wondering why it occurs...
Thank you in advance! :)
You must add L at the end of 3600 or 1000000:
Example:
long hour = 92233720368L / (3600 * 1000000L );
Here's what's hapenning:
System.out.println(3600 * 1000000); // Gives -694967296 because it exceeds the max limit of an integer size. So 92233720368L / -694967296 = -132
That's exactly what's happening in your division, the dominator is an integer and is considered as negative number for the reason I stated above. So in order to consider the multiplication result of type long you should add L after 3600 or after 1000000
It interprets 3600 and 10000000 as type int which cannot hold enough information to represent their product, and so you get a different number. You'd have to declare them both as type long to get the correct result.
I have a problem regarding really big numbers in Java.
I'm currently trying to convert a double consisting of a large number of seconds into years, days, hours, minutes and the seconds that are left.
My code looks like this: `
import java.util.Scanner;
public class timer {
public static void main(String[] args){
double sum = 1.1078087563769418E16;
double sec=0;
double min=0;
double hou=0;
double da=0;
double yea=0;
yea=sum/31536000;
int year = (int) yea;
sum=sum-year*31536000;
da=sum/86400;
int day = (int) da;
sum=sum-day*86400;
hou=sum/3600;
int hour = (int) hou;
sum=sum-hour*3600;
min=sum/60;
int minute = (int) min;
sum=sum-minute*60;
sec=sum;
int second = (int) sec;
sum=sum-second*60;
System.out.println(year+" "+day+" "+hour+" "+minute+" "+second);
}
}
`
When the double "sum" is as large as it is, the output gets weird. For example, the double "day" becomes larger than 365, which should be impossible.
Any solutions?
You are facing with a very common problem that most developers should know about: Integer overflow.
Your year variable is an int, the constant for second->year conversion is constant int, so int*int is... int. Except if your year is larger than approx 68, the result cannot fit into an int. Hence - overflow and silly results.
You have a couple of options available to you:
Do your timestamp arithmetic in longs. Really, that's the industry standard anyway.
If you insist on precision of over microseconds (or nano if you're concerned with last century only) - BigDecimal or BigInteger are your friends.
Use the TimeUnit class from concurrent package. It doesn't have years, but does have days and does conversion nicely (JodaTime would be even nicer though)
Overflow on the calculation sum=sum-year*31536000;
year and 31536000 are both integers, and their product is ~1E16, which is larger than java's max integer size. Use sum = sum-year*31536000.0 instead.
As a demonstration, add this code after you compute year:
System.out.println(year * 31536000.0); // 1.1078087556672E16
System.out.println(year * 31536000); // 1100687872
You can use java.math.BigDecimal class if you need to represent numbers with great precision.
If you need huge integers you can use java.math.BigInteger.
First use long not double then try this logic
long min = sum / (60) % 60;
long hou = sum / (60 * 60 )% 24;
long da = sum/(60*60*24)%30;
long yea = sum/(60*60*24*30)%365;
If that number is beyond the limit of long then use BigInteger but then this calculation will not work.
I thought long and Long class are more or less same thing.
I saw this link
When I displayed Long.MAX_VALUE it displayed 9223372036854775807.
But when I was doing multiplication of 1000000*1000000 which is 10^12 ; it gave overflow.
I was using long data type to store value...and while debugging it had value -727379968 after multiplication
Where am I making mistake or I am totally dumb?
Update: This was my code, and I got my mistake as specified in answer.
for (;;)
ppltn[i] = Integer.parseInt(tk.nextToken());
for (int i = 0; i < noc; i++) //sum is of long type
sum = sum + min * ppltn[i]; //min and ppltn are of integer type
The expression
1000000 * 1000000;
is integer multiplication as both operands are integers. Therefore you are limited by the max value of an integer.
You need to do long multiplication
1000000L * 1000000 /* L if you want it*/;
where at least one operand is a long and the other gets promoted to a long (if it isn't already).
In Java, ^ doesn't mean "power". It is a bitwise XOR operator.
therefore 10^6 means 10 XOR 6 instead 10 * 10 * 10 * 10 * 10 * 10
it is hard to guess without seeing your code.
However my guess is you are doing somehting like
long l = 1000000 * 10000000;
If so, here is the problem.
literal 1000000 is in fact an int instead of long, and therefore, 1000000 * 10000000 is doing a int multiplication and it got overflow (max of int is something around 2,xxx,xxx,xxx). The "overflowed" value is then cast to a long. Which give you the "strange" result.