2014-10-19 65 views
0

對於類,我必須編寫一個方法來檢查將某個有理數與整數相乘是否會導致溢出。如何縮短檢查乘法是否溢出的方法

我已經寫了下面的代碼和它的作品,但我有一種感覺這可能是短,但我不知道如何:

/** 
* A method for multiplying a rational number with a given number 
*/ 
public Rational multiply(long factor) { 
    try { 
     this.numerator = Math.multiplyExact(this.getNumerator(), factor); 
     return this; 
    } catch (ArithmeticException e) { 
     try { 
      this.numerator = Math.multiplyExact(Math.multiplyExact(this.getNumerator(),this.getNumerator()), factor); 
      this.denominator = this.denominator * this.denominator; 
      return this; 
     } catch (ArithmeticException e1) { 
      try { 
       this.numerator = Math.multiplyExact(Math.multiplyExact(this.getNumerator(),this.getNumerator()),Math.multiplyExact(factor, factor)); 
       this.denominator = this.denominator * this.denominator * this.denominator; 
       return this; 
      } catch (ArithmeticException e2) { 
       System.out.println("Overflow"); 
       return null; 
      } 
     } 
    } 
} 

的方法執行以下操作: A =分子,B =分母中,f =因子

  • 如果使用 「α* F」 不溢出不是返回(A * F)導致/ b
  • 如果它溢出比檢查的 「aa * F」 溢出,如果它不不是回報(aa * f)/ bb
  • 如果它溢出比檢查「AA * FF」溢出,如果它不高於收益率(AA * FF)/ BBB
+1

爲什麼你認爲乘以一個數字溢出與另一個數字它不會溢出? – 2014-10-19 12:35:12

+0

您可以檢查乘法的結果是否小於輸入值。如果這是真的,則發生溢出。這不會處理所有情況,但你也可以對這個因素進行一些檢查。就像Integer.MAX_VALUE%rational < factor -->溢出 – user 2014-10-19 12:53:15

+0

我認爲用BigIntegers你不必擔心溢出太多,所以除非有其他約束(比如性能問題),否則我會使用它們。 – 2014-10-19 20:49:57

回答

0

隨着Integer.MAX_VALUE % d你會得到你多少次乘d數以獲得最大值,如果這個值更小,那麼你的因子乘法將溢出。

public Rational multiply(Long factor) { 
    double d = this.numerator/(double) this.denumerator; 
    if(Integer.MAX_VALUE % d < factor){ 
     //overflow 
    } else if (this.numerator * factor < this.numerator){ 
     //overflow 
    }else{ 
     this.numerator *= factor; 
    } 
} 

編輯︰如果您的Rational對象表示-1和1之間的值您可以確保沒有溢出將發生。

+0

Java8中的Math#multiplyExact(http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#multiplyExact-long-long-)有什麼問題?我認爲這似乎是一個不錯的選擇。 – 2014-10-19 20:47:29

+0

@GáborBakosTrue!但我認爲num和denom被存儲爲int,並且他希望與long相乘。所以當使用multiplyExact時,TO必須在multiplyExact(int,int)或multiplyExact(long,long)之間進行選擇。 – user 2014-10-19 20:52:13