As already mentioned, using a “larger” data type allows you to check and easily calculate, but what if there is no larger data type?
You can mathematically test if this leads to overflow:
If you are caluclating base^power , it means base^power = result - it also means power-th square of result = base - The maximum allowed result is Integer.MAX_VALUE - otherwise you have an overflow.
power-th root ANY number greater than zero will ALWAYS fall within the range ]0,number] - there is no likelihood of arithmetic overflows.
So - compare the base you are using with power-th root Integer.MAX_VALUE - base LARGER ? Then you will encounter overflow - otherwise it will stick below (or be equal to) the result of Integer.MAX_VALUE
private static double powSafe(double base, int pow){ //this is the p-th root of the maximum integer allowed double root = Math.pow(Integer.MAX_VALUE, 1.0/pow); if (root < base){ throw new ArithmeticException("The calculation of " + base + "^" + pow + " would overflow."); }else{ return Math.pow(base, pow); } } public static void main(String[] argv) { double rootOfMaxInt = Math.pow(Integer.MAX_VALUE, 1.0/2); try{ //that should be INTEGER.MAX_VALUE, so valid. double d1 = powSafe(rootOfMaxInt, 2); System.out.println(rootOfMaxInt + "^2 = " + d1); }catch (ArithmeticException e){ System.out.println(e.getMessage()); } try{ //this should overflow cause "+1" double d2 = powSafe(rootOfMaxInt +1, 2); System.out.println("("rootOfMaxInt + "+ 1)^2 = " + d1); }catch (ArithmeticException e){ System.out.println(e.getMessage()); } double the67thRootOfMaxInt = Math.pow(Integer.MAX_VALUE, 1.0/67); try{ //and so, it continues double d3 = powSafe(the67thRootOfMaxInt, 67); System.out.println(the67thRootOfMaxInt + "^67 = " + d3); double d4 = powSafe(the67thRootOfMaxInt +1, 67); System.out.println("(" + the67thRootOfMaxInt + " + 1)^67 = " + d3); }catch (ArithmeticException e){ System.out.println(e.getMessage()); } }
leads to
46340.950001051984^2 = 2.147483647E9 The calculation of 46341.950001051984^2 would overflow. 1.3781057199632372^67 = 2.1474836470000062E9 The calculation of 2.378105719963237^67 would overflow.
Note that inaccuracies appear because double does not have infinite precision, which already truncates the expression 2nd square of Integer.Max_Value , the reason Integer.MAX_VALUE odd.
source share