1

How can be possibly determine if squaring an integer is causing overflow. All the number greater than 46340 have square value greater than maximum integer value of java. Since java will wrap the numbers squaring 46431 gives -2147479015 whereas squaring 2147483647 gives 1, so that further complicates. Also unfortunately I cannot do this in Java 8 which would have thrown ArithmeticException. So is there any other possible way of checking if squaring an integer is causing overflow or not?

2
  • 5
    Simple. Just see if it is greater than 46340. Commented Jun 19, 2015 at 23:33
  • 1
    @hexafraction: Or less than -46340! Commented Jun 19, 2015 at 23:39

4 Answers 4

5
public class SecureSquare {

    private static final double SECURE_SQUARE_LIMIT = Math.sqrt(Integer.MAX_VALUE);

    public static int square(int number) {
        if (Math.abs(number) > SECURE_SQUARE_LIMIT) {
            throw new ArithmeticException("Square overflow exception!");
        }
        return number * number;
    }

    public static void main(String[] args) {
        int number = square(-46340);
        System.out.println(number);
    }
}

Output for 43640:

2147395600

Output for 43641:

Exception in thread "main" java.lang.ArithmeticException: Square overflow exception!
    at com.artofcode.test.SecureSquare.square(SecureSquare.java:9)
    at com.artofcode.test.SecureSquare.main(SecureSquare.java:15)
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

Since Math.sqrt(Integer.MAX_VALUE) is known to be roughly 46340 it seems a shame to calculate it every time rather than use a const.
@bhspencer, now I decalare it as a constant! Roughly 46340 make it a magic number and not easy to understand
2
public boolean isSquareCauseOverflow(int n) {
    if (n > 46340 || n < -46340) return true;
    else return false;
}

2 Comments

Or return n > 46340;
yep, or not even put it in a function. Just trying to make it super obvious for the OP.
1

Not fully aware of your usecase, but you can put a limit on the input to your method which returns the squared value. And this limit can be sqrt of Integer.MAX.

Otherwise - you can use something like BigInteger to perform your calculations.

Comments

0

Also unfortunately I cannot do this in Java 8 which would have thrown ArithmeticException.

That is not correct. Integer overflow does not cause an exception. You only get an exception on integer divide by zero. This applies for all extant versions of Java.

AFAIK, there is no general test to see if a primitive integer arithmetic operation1 has caused an overflow.

For any specific case you can devise a test either based on a mathematical analysis or by doing an equivalent operation sequence using long or BigInteger.

For example:

 int number = ...
 int square = number * number;
 long longSquare = ((long) number) * ((long) number);
 if (square != longSquare) {
     System.out.println("Overflow occurred");
 }

(I think: there might possibly be edge cases in the above involving Integer.MIN_VALUE. If you use BigInteger then there should not be any edge cases.)


In this case, the test to see if it will cause an overflow is trivial, and there is no need for more complicated alternatives.


1 - In Java 8, some new "exact" integer arithmetic methods were added to the Math class. These throw ArithmeticException in the event of overflow. However, the behaviour of the primitive arithmetic operators has not changed.

4 Comments

I believe, he was talking about this docs.oracle.com/javase/8/docs/api/java/lang/…
@JiriKremser - Given the context, I don't. He is saying that he cannot do "this" in Java 8, where the "this" is something that he can do in Java 7. Clearly, that can't be referring to those methods ... 'cos they don't exist in Java 7. That sentence only makes any sense if he is referring to primitive integer arithmetic.
imho, "this" == ${subject} :]
No. This is the computation described in the previous sentence. Either way, the OP's implication is that you can do it in Java 7 but not Java 8, which makes no sense if the OP is talking about the Java 8-only methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.