2014-10-19 1 views
0

클래스의 경우 특정 유리수를 정수로 곱하면 오버플로가 발생하는지 확인하는 메서드를 작성해야합니다.곱셈에 오버플로가 있는지 확인하는 방법을 줄이는 방법

나는 다음 코드를 작성하고 그것을 작동하지만 나는이 짧아 질 수 있습니다 느낌했지만 나는 방법을 모른다 : A = 분자, B = 분모 :

/** 
* 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; 
      } 
     } 
    } 
} 

방법은 다음을 수행 , F = 인자

  • "는 * f는"리턴 (a *의 F)보다 오버 플로우가 발생하지 않으면/B
  • 그것이 않음 "단 *의 F"가 오버 플로우하는 경우, 만약 확인보다 오버플 않으면 return (aa * f)/bb보다
  • 그것은 당신이 D를 곱 수있는 횟수의 수를 얻을 것이다 Integer.MAX_VALUE % d으로하는 경우 "AA의 *의 FF"오버 플로우, 그것은 반환보다하지 않는 경우 (AA의 *의 FF)/BBB
+1

오버플로 된 숫자에 다른 숫자가 오버 플로우되지 않는 이유는 무엇입니까? –

+0

곱셈의 결과가 입력 값보다 작은 지 확인할 수 있습니다. 이것이 사실이면 오버 플로우가 발생했습니다. 이것은 모든 경우를 다루지는 않을 것입니다 만, 당신은 또한 몇 가지 검사를 수행 할 수 있습니다. If Integer.MAX_VALUE % reasonational < factor --> overflow – user

+0

BigIntegers를 사용하면 오버플로에 대해 너무 걱정할 필요가 없으므로 (성능 문제와 같은) 다른 제약 조건이 없으면 사용할 것입니다. –

답변

0

을 확인보다 오버 플로우를 수행하는 경우 최대 값을 얻고이 값이 더 작 으면 곱셈이 오버플로됩니다.

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

EDIT : Rational 객체가 -1과 1 사이의 값을 나타내는 경우 오버플로가 발생하지 않을 것입니다.

+0

Java8에서 Math # multiplyExact (http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#multiplyExact-long-long-)의 문제점은 무엇입니까? 나는 그것이 좋은 선택 인 것 같다. –

+0

@ GáborBakos 사실! 하지만 num과 denom은 int로 저장되어 있고 long으로 곱셈되기를 원한다고 생각합니다. 따라서 multiplyExact를 사용할 때 TO는 multiplyExact (int, int) 또는 multiplyExact (long, long) 중에서 선택해야합니다. – user

관련 문제