/** * Returns the integer square root of this integer. * * @return <code>k<code> such as <code>k^2 <= this < (k + 1)^2</code> * @throws ArithmeticException * if this integer is negative. */ public IInteger sqrt() { return nthRoot(2); }
/** * Returns the nth-root of this integer. * * @return <code>k<code> such as <code>k^n <= this < (k + 1)^n</code> * @throws ArithmeticException * if this integer is negative and n is even. */ public IInteger nthRoot(int n) throws ArithmeticException { if (sign() == 0) { return IntegerSym.valueOf(0); } else if (sign() < 0) { if (n % 2 == 0) { // even exponent n throw new ArithmeticException(); } else { // odd exponent n return (IntegerSym) ((IntegerSym) negate()).nthRoot(n).negate(); } } else { IntegerSym result; IntegerSym temp = this; do { result = temp; temp = divideAndRemainder(temp.pow(n - 1))[0].add(temp.multiply(IntegerSym.valueOf(n - 1))).divideAndRemainder( IntegerSym.valueOf(n))[0]; } while (temp.compareTo(result) < 0); return result; } }