2015-06-19 30 views
1

怎樣才能確定平方整數是否導致溢出。所有大於46340的數字的平方值都大於java的最大整數值。由於java會將數字平方46431給出-2147479015,而平方2147483647給出1,所以更復雜。另外不幸的是,我不能在Java 8中這樣做,因爲它會拋出ArithmeticException。那麼是否有其他可能的方法檢查整數是否導致溢出?Java檢查平方整數是否導致溢出

+5

簡單。只是看它是否大於46340. – hexafraction

+1

@hexafraction:或小於-46340! – user2357112

回答

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); 
    } 
} 

輸出爲43640:

2147395600 

輸出爲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) 
    ... 
+0

由於Math.sqrt(整數。MAX_VALUE)大概是46340,但每次計算它似乎都是一種恥辱,而不是使用const。 – bhspencer

+2

@bhspencer,現在我把它作爲一個常量!大約46340使它成爲一個神奇的數字,不容易理解 –

1

不完全知道您的用例,但您可以對返回平方值的方法的輸入進行限制。這個限制可以是Integer.MAX的sqrt。

否則 - 您可以使用類似BigInteger的內容來執行計算。

2
public boolean isSquareCauseOverflow(int n) { 
    if (n > 46340 || n < -46340) return true; 
    else return false; 
} 
+0

或'return n> 46340;' – Pshemo

+0

是的,或者甚至沒有把它放在函數中。只是試圖讓OP非常明顯。 – bhspencer

0

而且不幸的是我也不會在Java 8中會拋出ArithmeticException做到這一點。

這是不正確的。整數溢出不會導致異常。你只會得到整數除零的例外。這適用於所有現存的Java版本。如果原始整數算術運算 導致溢出,則沒有通用測試。

對於任何特定情況,您可以基於數學分析或通過使用longBigInteger執行等效操作序列來設計測試。

例如:

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

(我想:可能有可能是邊緣的情況下在上述涉及Integer.MIN_VALUE如果使用BigInteger那麼不應該有任何優勢的情況下。)


在這種情況下,測試會導致溢出是微不足道的,並且不需要更復雜的替代方案。


1 - 在Java 8中,一些新的 「精確」 的整數運算方法添加到Math類。如果發生溢出,這些會拋出ArithmeticException。但是,基本算術運算符的行爲並沒有改變。

+0

我相信,他在談論這個https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#multiplyExact-int -int- –

+0

@JiriKremser - 鑑於上下文,我不知道。他說他不能在Java 8中執行「this」,而這個「this」是他可以在Java 7中完成的事情。顯然,這不能指那些方法......因爲它們不存在在Java 7中。如果他指的是原始整數算術,那麼這句話就有意義。 –

+0

imho,「this」== $ {subject}:] –