对于类,我必须编写一个方法来检查是否将某个有理数与一个整数相乘会导致溢出。
我已经编写了以下代码并且它有效,但我觉得它可能会更短但我不知道如何:
/**
* 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 =因子
答案 0 :(得分: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之间的值,则可以确保不会发生溢出。