Skip to main content

ArithmeticException

java.lang.ArithmeticException

ArithmeticException is described in the javadoc comments as:

Thrown when an exceptional arithmetic condition has occurred. For example, an integer 'divide by zero' throws an instance of this class.
author: unascribed version: 1.22, 12/19/03 since: JDK1.0

Where is this exception thrown?

Following, is a list of exception messages cross-referenced to the source code responsible for throwing them. Click on the method link to view the code and see how the exception is thrown.

How is this exception thrown?

The following sub-sections identify where this exception is thrown, and how (or why) the code is throwing the exception.

Any source code quoted in this section is subject to the Java Research License unless stated otherwise.

java.math.MutableBigInteger.divide(MutableBigInteger, MutableBigInteger, MutableBigInteger)

/**
     * Calculates the quotient and remainder of this div b and places them
     * in the MutableBigInteger objects provided.
     * Uses Algorithm D in Knuth section 4.3.1.
     * Many optimizations to that algorithm have been adapted from the Colin
     * Plumb C library.
     * It special cases one word divisors for speed.
     * The contents of a and b are not changed.
     */
void divide(MutableBigInteger b, MutableBigInteger quotient, MutableBigInteger rem) {
    if (b.intLen == 0) throw new ArithmeticException('BigInteger divide by zero');
    if (intLen == 0) {
        quotient.intLen = quotient.offset = rem.intLen = rem.offset = 0;
        return;
    }
    int cmp = compare(b);
    if (cmp < 0) {
        quotient.intLen = quotient.offset = 0;
        rem.copyValue(this);
        return;
    }
    if (cmp == 0) {
        quotient.value[0] = quotient.intLen = 1;
        quotient.offset = rem.intLen = rem.offset = 0;
        return;
    }
    quotient.clear();
    if (b.intLen == 1) {
        rem.copyValue(this);
        rem.divideOneWord(b.value[b.offset], quotient);
        return;
    }
    int[] d = new int[b.intLen];
    for (int i = 0; i < b.intLen; i++) d[i] = b.value[b.offset + i];
    int dlen = b.intLen;
    if (rem.value.length < intLen + 1) rem.value = new int[intLen + 1];
    for (int i = 0; i < intLen; i++) rem.value[i + 1] = value[i + offset];
    rem.intLen = intLen;
    rem.offset = 1;
    int nlen = rem.intLen;
    int limit = nlen - dlen + 1;
    if (quotient.value.length < limit) {
        quotient.value = new int[limit];
        quotient.offset = 0;
    }
    quotient.intLen = limit;
    int[] q = quotient.value;
    int shift = 32 - BigInteger.bitLen(d[0]);
    if (shift > 0) {
        BigInteger.primitiveLeftShift(d, dlen, shift);
        rem.leftShift(shift);
    }
    if (rem.intLen == nlen) {
        rem.offset = 0;
        rem.value[0] = 0;
        rem.intLen++;
    }
    int dh = d[0];
    long dhLong = dh & LONG_MASK;
    int dl = d[1];
    int[] qWord = new int[2];
    for (int j = 0; j < limit; j++) {
        int qhat = 0;
        int qrem = 0;
        boolean skipCorrection = false;
        int nh = rem.value[j + rem.offset];
        int nh2 = nh + 0x80000000;
        int nm = rem.value[j + 1 + rem.offset];
        if (nh == dh) {
            qhat = ~0;
            qrem = nh + nm;
            skipCorrection = qrem + 0x80000000 < nh2;
        } else {
            long nChunk = (((long) nh) << 32) | (nm & LONG_MASK);
            if (nChunk >= 0) {
                qhat = (int) (nChunk / dhLong);
                qrem = (int) (nChunk - (qhat * dhLong));
            } else {
                divWord(qWord, nChunk, dh);
                qhat = qWord[0];
                qrem = qWord[1];
            }
        }
        if (qhat == 0) continue;
        if (!skipCorrection) {
            long nl = rem.value[j + 2 + rem.offset] & LONG_MASK;
            long rs = ((qrem & LONG_MASK) << 32) | nl;
            long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
            if (unsignedLongCompare(estProduct, rs)) {
                qhat--;
                qrem = (int) ((qrem & LONG_MASK) + dhLong);
                if ((qrem & LONG_MASK) >= dhLong) {
                    estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
                    rs = ((qrem & LONG_MASK) << 32) | nl;
                    if (unsignedLongCompare(estProduct, rs)) qhat--;
                }
            }
        }
        rem.value[j + rem.offset] = 0;
        int borrow = mulsub(rem.value, d, qhat, dlen, j + rem.offset);
        if (borrow + 0x80000000 > nh2) {
            divadd(d, rem.value, j + 1 + rem.offset);
            qhat--;
        }
        q[j] = qhat;
    }
    if (shift > 0) rem.rightShift(shift);
    rem.normalize();
    quotient.normalize();
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.MutableBigInteger.euclidModInverse(int)

/**
     * Uses the extended Euclidean algorithm to compute the modInverse of base
     * mod a modulus that is a power of 2. The modulus is 2^k.
     */
MutableBigInteger euclidModInverse(int k) {
    MutableBigInteger b = new MutableBigInteger(1);
    b.leftShift(k);
    MutableBigInteger mod = new MutableBigInteger(b);
    MutableBigInteger a = new MutableBigInteger(this);
    MutableBigInteger q = new MutableBigInteger();
    MutableBigInteger r = new MutableBigInteger();
    b.divide(a, q, r);
    MutableBigInteger swapper = b;
    b = r;
    r = swapper;
    MutableBigInteger t1 = new MutableBigInteger(q);
    MutableBigInteger t0 = new MutableBigInteger(1);
    MutableBigInteger temp = new MutableBigInteger();
    while (!b.isOne()) {
        a.divide(b, q, r);
        if (r.intLen == 0) throw new ArithmeticException('BigInteger not invertible.');
        swapper = r;
        r = a;
        a = swapper;
        if (q.intLen == 1) t1.mul(q.value[q.offset], temp); else q.multiply(t1, temp);
        swapper = q;
        q = temp;
        temp = swapper;
        t0.add(q);
        if (a.isOne()) return t0;
        b.divide(a, q, r);
        if (r.intLen == 0) throw new ArithmeticException('BigInteger not invertible.');
        swapper = b;
        b = r;
        r = swapper;
        if (q.intLen == 1) t0.mul(q.value[q.offset], temp); else q.multiply(t0, temp);
        swapper = q;
        q = temp;
        temp = swapper;
        t1.add(q);
    }
    mod.subtract(t1);
    return mod;
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.MutableBigInteger.modInverse(MutableBigInteger)

/**
     * Calculate the multiplicative inverse of this mod mod, where mod is odd.
     * This and mod are not changed by the calculation.
     * This method implements an algorithm due to Richard Schroeppel, that uses
     * the same intermediate representation as Montgomery Reduction
     * ('Montgomery Form').  The algorithm is described in an unpublished
     * manuscript entitled 'Fast Modular Reciprocals.'
     */
private MutableBigInteger modInverse(MutableBigInteger mod) {
    MutableBigInteger p = new MutableBigInteger(mod);
    MutableBigInteger f = new MutableBigInteger(this);
    MutableBigInteger g = new MutableBigInteger(p);
    SignedMutableBigInteger c = new SignedMutableBigInteger(1);
    SignedMutableBigInteger d = new SignedMutableBigInteger();
    MutableBigInteger temp = null;
    SignedMutableBigInteger sTemp = null;
    int k = 0;
    if (f.isEven()) {
        int trailingZeros = f.getLowestSetBit();
        f.rightShift(trailingZeros);
        d.leftShift(trailingZeros);
        k = trailingZeros;
    }
    while (!f.isOne()) {
        if (f.isZero()) throw new ArithmeticException('BigInteger not invertible.');
        if (f.compare(g) < 0) {
            temp = f;
            f = g;
            g = temp;
            sTemp = d;
            d = c;
            c = sTemp;
        }
        if (((f.value[f.offset + f.intLen - 1] ^ g.value[g.offset + g.intLen - 1]) & 3) == 0) {
            f.subtract(g);
            c.signedSubtract(d);
        } else {
            f.add(g);
            c.signedAdd(d);
        }
        int trailingZeros = f.getLowestSetBit();
        f.rightShift(trailingZeros);
        d.leftShift(trailingZeros);
        k += trailingZeros;
    }
    while (c.sign < 0) c.signedAdd(p);
    return fixup(c, p, k);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.MutableBigInteger.mutableModInverse(MutableBigInteger)

/**
     * Returns the modInverse of this mod p. This and p are not affected by
     * the operation.
     */
MutableBigInteger mutableModInverse(MutableBigInteger p) {
    if (p.isOdd()) return modInverse(p);
    if (isEven()) throw new ArithmeticException('BigInteger not invertible.');
    int powersOf2 = p.getLowestSetBit();
    MutableBigInteger oddMod = new MutableBigInteger(p);
    oddMod.rightShift(powersOf2);
    if (oddMod.isOne()) return modInverseMP2(powersOf2);
    MutableBigInteger oddPart = modInverse(oddMod);
    MutableBigInteger evenPart = modInverseMP2(powersOf2);
    MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2);
    MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2);
    MutableBigInteger temp1 = new MutableBigInteger();
    MutableBigInteger temp2 = new MutableBigInteger();
    MutableBigInteger result = new MutableBigInteger();
    oddPart.leftShift(powersOf2);
    oddPart.multiply(y1, result);
    evenPart.multiply(oddMod, temp1);
    temp1.multiply(y2, temp2);
    result.add(temp2);
    result.divide(p, temp1, temp2);
    return temp2;
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.mod(BigInteger)

/**
     * Returns a BigInteger whose value is <tt>(this mod m</tt>).  This method
     * differs from <tt>remainder</tt> in that it always returns a
     * <i>non-negative</i> BigInteger.
     * @param  m the modulus.
     * @return <tt>this mod m</tt>
     * @throws ArithmeticException <tt>m <= 0</tt>
     * @see    #remainder
     */
public BigInteger mod(BigInteger m) {
    if (m.signum <= 0) throw new ArithmeticException('BigInteger: modulus not positive');
    BigInteger result = this.remainder(m);
    return (result.signum >= 0 ? result : result.add(m));
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.modInverse(BigInteger)

/**
     * Returns a BigInteger whose value is <tt>(this<sup>-1</sup> mod m)</tt>.
     * @param  m the modulus.
     * @return <tt>this<sup>-1</sup> mod m</tt>.
     * @throws ArithmeticException <tt> m <= 0</tt>, or this BigInteger
     *        has no multiplicative inverse mod m (that is, this BigInteger
     *        is not <i>relatively prime</i> to m).
     */
public BigInteger modInverse(BigInteger m) {
    if (m.signum != 1) throw new ArithmeticException('BigInteger: modulus not positive');
    if (m.equals(ONE)) return ZERO;
    BigInteger modVal = this;
    if (signum < 0 || (intArrayCmp(mag, m.mag) >= 0)) modVal = this.mod(m);
    if (modVal.equals(ONE)) return ONE;
    MutableBigInteger a = new MutableBigInteger(modVal);
    MutableBigInteger b = new MutableBigInteger(m);
    MutableBigInteger result = a.mutableModInverse(b);
    return new BigInteger(result, 1);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.modPow(BigInteger, BigInteger)

/**
     * Returns a BigInteger whose value is
     * <tt>(this<sup>exponent</sup> mod m)</tt>.  (Unlike <tt>pow</tt>, this
     * method permits negative exponents.)
     * @param  exponent the exponent.
     * @param  m the modulus.
     * @return <tt>this<sup>exponent</sup> mod m</tt>
     * @throws ArithmeticException <tt>m <= 0</tt>
     * @see    #modInverse
     */
public BigInteger modPow(BigInteger exponent, BigInteger m) {
    if (m.signum <= 0) throw new ArithmeticException('BigInteger: modulus not positive');
    if (exponent.signum == 0) return (m.equals(ONE) ? ZERO : ONE);
    if (this.equals(ONE)) return (m.equals(ONE) ? ZERO : ONE);
    if (this.equals(ZERO) && exponent.signum >= 0) return ZERO;
    if (this.equals(negConst[1]) && (!exponent.testBit(0))) return (m.equals(ONE) ? ZERO : ONE);
    boolean invertResult;
    if ((invertResult = (exponent.signum < 0))) exponent = exponent.negate();
    BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0 ? this.mod(m) : this);
    BigInteger result;
    if (m.testBit(0)) {
        result = base.oddModPow(exponent, m);
    } else {
        int p = m.getLowestSetBit();
        BigInteger m1 = m.shiftRight(p);
        BigInteger m2 = ONE.shiftLeft(p);
        BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0 ? this.mod(m1) : this);
        BigInteger a1 = (m1.equals(ONE) ? ZERO : base2.oddModPow(exponent, m1));
        BigInteger a2 = base.modPow2(exponent, p);
        BigInteger y1 = m2.modInverse(m1);
        BigInteger y2 = m1.modInverse(m2);
        result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
    }
    return (invertResult ? result.modInverse(m) : result);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.divide(BigDecimal)

/**
     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
     * divisor)</tt>, and whose preferred scale is <tt>(this.scale() -
     * divisor.scale())</tt>; if the exact quotient cannot be
     * represented (because it has a non-terminating decimal
     * expansion) an <tt>ArithmeticException</tt> is thrown.
     * @param  divisor value by which this <tt>BigDecimal</tt> is to be divided.
     * @throws ArithmeticException if the exact quotient does not have a
     *         terminating decimal expansion
     * @return <tt>this / divisor</tt>
     * @since 1.5
     * @author Joseph D. Darcy
     */
public BigDecimal divide(BigDecimal divisor) {
    if (divisor.signum() == 0) {
        if (this.signum() == 0) throw new ArithmeticException('Division undefined');
        throw new ArithmeticException('Division by zero');
    }
    int preferredScale = (int) Math.max(Math.min((long) this.scale() - divisor.scale(), Integer.MAX_VALUE), Integer.MIN_VALUE);
    if (this.signum() == 0) return new BigDecimal(0, preferredScale); else {
        this.inflate();
        divisor.inflate();
        MathContext mc = new MathContext((int) Math.min(this.precision() + (long) Math.ceil(10.0 * divisor.precision() / 3.0), Integer.MAX_VALUE), RoundingMode.UNNECESSARY);
        BigDecimal quotient;
        try {
            quotient = this.divide(divisor, mc);
        } catch (ArithmeticException e) {
            throw new ArithmeticException('Non-terminating decimal expansion; ' + 'no exact representable decimal result.');
        }
        int quotientScale = quotient.scale();
        if (preferredScale > quotientScale) return quotient.setScale(preferredScale);
        return quotient;
    }
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.divide(BigDecimal, MathContext)

/**
     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
     * divisor)</tt>, with rounding according to the context settings.
     * @param  divisor value by which this <tt>BigDecimal</tt> is to be divided.
     * @param  mc the context to use.
     * @return <tt>this / divisor</tt>, rounded as necessary.
     * @throws ArithmeticException if the result is inexact but the
     *         rounding mode is <tt>UNNECESSARY</tt> or 
     *         <tt>mc.precision == 0</tt> and the quotient has a 
     *         non-terminating decimal expansion.
     * @since  1.5
     */
public BigDecimal divide(BigDecimal divisor, MathContext mc) {
    if (mc.precision == 0) return divide(divisor);
    BigDecimal lhs = this.inflate();
    BigDecimal rhs = divisor.inflate();
    BigDecimal result;
    long preferredScale = (long) lhs.scale() - rhs.scale();
    if (rhs.signum() == 0) {
        if (lhs.signum() == 0) throw new ArithmeticException('Division undefined');
        throw new ArithmeticException('Division by zero');
    }
    if (lhs.signum() == 0) return new BigDecimal(BigInteger.ZERO, (int) Math.max(Math.min(preferredScale, Integer.MAX_VALUE), Integer.MIN_VALUE));
    BigDecimal xprime = new BigDecimal(lhs.intVal.abs(), lhs.precision());
    BigDecimal yprime = new BigDecimal(rhs.intVal.abs(), rhs.precision());
    if (mc.roundingMode == RoundingMode.CEILING || mc.roundingMode == RoundingMode.FLOOR) {
        if ((xprime.signum() != lhs.signum()) ^ (yprime.signum() != rhs.signum())) {
            mc = new MathContext(mc.precision, (mc.roundingMode == RoundingMode.CEILING) ? RoundingMode.FLOOR : RoundingMode.CEILING);
        }
    }
    if (xprime.compareTo(yprime) > 0) yprime.scale -= 1;
    result = xprime.divide(yprime, mc.precision, mc.roundingMode.oldMode);
    result.scale = checkScale((long) yprime.scale - xprime.scale - (rhs.scale - lhs.scale) + mc.precision);
    if (lhs.signum() != rhs.signum()) result = result.negate();
    result = result.doRound(mc);
    if (result.multiply(divisor).compareTo(this) == 0) {
        return result.stripZerosToMatchScale(preferredScale);
    } else {
        return result;
    }
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.divideToIntegralValue(BigDecimal, MathContext)

/**
     * Returns a <tt>BigDecimal</tt> whose value is the integer part
     * of <tt>(this / divisor)</tt>.  Since the integer part of the
     * exact quotient does not depend on the rounding mode, the
     * rounding mode does not affect the values returned by this
     * method.  The preferred scale of the result is
     * <code>(this.scale() - divisor.scale())</code>.  An
     * <tt>ArithmeticException</tt> is thrown if the integer part of
     * the exact quotient needs more than <tt>mc.precision</tt>
     * digits.
     * @param  divisor value by which this <tt>BigDecimal</tt> is to be divided.
     * @param  mc the context to use.
     * @return The integer part of <tt>this / divisor</tt>.
     * @throws ArithmeticException if <tt>divisor==0</tt>
     * @throws ArithmeticException if <tt>mc.precision</tt> > 0 and the result
     *         requires a precision of more than <tt>mc.precision</tt> digits.
     * @since  1.5
     * @author Joseph D. Darcy
     */
public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
    if (mc.precision == 0 || (this.abs().compareTo(divisor.abs()) < 0)) return divideToIntegralValue(divisor);
    int preferredScale = (int) Math.max(Math.min((long) this.scale() - divisor.scale(), Integer.MAX_VALUE), Integer.MIN_VALUE);
    BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
    int resultScale = result.scale();
    if (result.scale() < 0) {
        BigDecimal product = result.multiply(divisor);
        if (this.subtract(product).abs().compareTo(divisor.abs()) >= 0) {
            throw new ArithmeticException('Division impossible');
        }
    } else if (result.scale() > 0) {
        result = result.setScale(0, RoundingMode.DOWN);
    }
    int precisionDiff;
    if ((preferredScale > result.scale()) && (precisionDiff = mc.precision - result.precision()) > 0) {
        return result.setScale(result.scale() + Math.min(precisionDiff, preferredScale - result.scale));
    } else return result.stripZerosToMatchScale(preferredScale);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.pow(int)

/**
     * Returns a <tt>BigDecimal</tt> whose value is
     * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
     * unlimited precision.
     * The parameter <tt>n</tt> must be in the range 0 through
     * 999999999, inclusive.  <tt>ZERO.pow(0)</tt> returns {@link
     * #ONE}.
     * Note that future releases may expand the allowable exponent
     * range of this method.
     * @param  n power to raise this <tt>BigDecimal</tt> to.
     * @return <tt>this<sup>n</sup></tt>
     * @throws ArithmeticException if <tt>n</tt> is out of range.
     * @since  1.5
     */
public BigDecimal pow(int n) {
    if (n < 0 || n > 999999999) throw new ArithmeticException('Invalid operation');
    int newScale = checkScale((long) scale * n);
    this.inflate();
    return new BigDecimal(intVal.pow(n), newScale);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.pow(int, MathContext)

/**
     * Returns a <tt>BigDecimal</tt> whose value is
     * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
     * the core algorithm defined in ANSI standard X3.274-1996 with
     * rounding according to the context settings.  In general, the
     * returned numerical value is within two ulps of the exact
     * numerical value for the chosen precision.  Note that future
     * releases may use a different algorithm with a decreased
     * allowable error bound and increased allowable exponent range.
     * The X3.274-1996 algorithm is:
     * <ul>
     * <li> An <tt>ArithmeticException</tt> exception is thrown if
     *  <ul>
     *    <li><tt>abs(n) > 999999999</tt>
     *    <li><tt>mc.precision == 0</tt> and <tt>n < 0</tt>
     *    <li><tt>mc.precision > 0</tt> and <tt>n</tt> has more than
     *    <tt>mc.precision</tt> decimal digits
     *  </ul>
     * <li> if <tt>n</tt> is zero, {@link #ONE} is returned even if
     * <tt>this</tt> is zero, otherwise
     * <ul>
     *   <li> if <tt>n</tt> is positive, the result is calculated via
     *   the repeated squaring technique into a single accumulator.
     *   The individual multiplications with the accumulator use the
     *   same math context settings as in <tt>mc</tt> except for a
     *   precision increased to <tt>mc.precision + elength + 1</tt>
     *   where <tt>elength</tt> is the number of decimal digits in
     *   <tt>n</tt>.
     *   <li> if <tt>n</tt> is negative, the result is calculated as if
     *   <tt>n</tt> were positive; this value is then divided into one
     *   using the working precision specified above.
     *   <li> The final value from either the positive or negative case
     *   is then rounded to the destination precision.
     *   </ul>
     * </ul>
     * @param  n power to raise this <tt>BigDecimal</tt> to.
     * @param  mc the context to use.
     * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
     *         algorithm
     * @throws ArithmeticException if the result is inexact but the
     *         rounding mode is <tt>UNNECESSARY</tt>, or <tt>n</tt> is out 
     *         of range.
     * @since  1.5
     */
public BigDecimal pow(int n, MathContext mc) {
    if (mc.precision == 0) return pow(n);
    if (n < -999999999 || n > 999999999) throw new ArithmeticException('Invalid operation');
    if (n == 0) return ONE;
    this.inflate();
    BigDecimal lhs = this;
    MathContext workmc = mc;
    int mag = Math.abs(n);
    if (mc.precision > 0) {
        int elength = intLength(mag);
        if (elength > mc.precision) throw new ArithmeticException('Invalid operation');
        workmc = new MathContext(mc.precision + elength + 1, mc.roundingMode);
    }
    BigDecimal acc = ONE;
    boolean seenbit = false;
    for (int i = 1; ; i++) {
        mag += mag;
        if (mag < 0) {
            seenbit = true;
            acc = acc.multiply(lhs, workmc);
        }
        if (i == 31) break;
        if (seenbit) acc = acc.multiply(acc, workmc);
    }
    if (n < 0) acc = ONE.divide(acc, workmc);
    return acc.doRound(mc);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.clearBit(int)

/**
     * Returns a BigInteger whose value is equivalent to this BigInteger
     * with the designated bit cleared.
     * (Computes <tt>(this & ~(1<<n))</tt>.)
     * @param  n index of bit to clear.
     * @return <tt>this & ~(1<<n)</tt>
     * @throws ArithmeticException <tt>n</tt> is negative.
     */
public BigInteger clearBit(int n) {
    if (n < 0) throw new ArithmeticException('Negative bit address');
    int intNum = n / 32;
    int[] result = new int[Math.max(intLength(), (n + 1) / 32 + 1)];
    for (int i = 0; i < result.length; i++) result[result.length - i - 1] = getInt(i);
    result[result.length - intNum - 1] &= ~(1 << (n % 32));
    return valueOf(result);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.flipBit(int)

/**
     * Returns a BigInteger whose value is equivalent to this BigInteger
     * with the designated bit flipped.
     * (Computes <tt>(this ^ (1<<n))</tt>.)
     * @param  n index of bit to flip.
     * @return <tt>this ^ (1<<n)</tt>
     * @throws ArithmeticException <tt>n</tt> is negative.
     */
public BigInteger flipBit(int n) {
    if (n < 0) throw new ArithmeticException('Negative bit address');
    int intNum = n / 32;
    int[] result = new int[Math.max(intLength(), intNum + 2)];
    for (int i = 0; i < result.length; i++) result[result.length - i - 1] = getInt(i);
    result[result.length - intNum - 1] ^= (1 << (n % 32));
    return valueOf(result);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.setBit(int)

/**
     * Returns a BigInteger whose value is equivalent to this BigInteger
     * with the designated bit set.  (Computes <tt>(this | (1<<n))</tt>.)
     * @param  n index of bit to set.
     * @return <tt>this | (1<<n)</tt>
     * @throws ArithmeticException <tt>n</tt> is negative.
     */
public BigInteger setBit(int n) {
    if (n < 0) throw new ArithmeticException('Negative bit address');
    int intNum = n / 32;
    int[] result = new int[Math.max(intLength(), intNum + 2)];
    for (int i = 0; i < result.length; i++) result[result.length - i - 1] = getInt(i);
    result[result.length - intNum - 1] |= (1 << (n % 32));
    return valueOf(result);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.testBit(int)

/**
     * Returns <tt>true</tt> if and only if the designated bit is set.
     * (Computes <tt>((this & (1<<n)) != 0)</tt>.)
     * @param  n index of bit to test.
     * @return <tt>true</tt> if and only if the designated bit is set.
     * @throws ArithmeticException <tt>n</tt> is negative.
     */
public boolean testBit(int n) {
    if (n < 0) throw new ArithmeticException('Negative bit address');
    return (getInt(n / 32) & (1 << (n % 32))) != 0;
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.pow(int)

/**
     * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
     * Note that <tt>exponent</tt> is an integer rather than a BigInteger.
     * @param  exponent exponent to which this BigInteger is to be raised.
     * @return <tt>this<sup>exponent</sup></tt>
     * @throws ArithmeticException <tt>exponent</tt> is negative.  (This would
     *        cause the operation to yield a non-integer value.)
     */
public BigInteger pow(int exponent) {
    if (exponent < 0) throw new ArithmeticException('Negative exponent');
    if (signum == 0) return (exponent == 0 ? ONE : this);
    int newSign = (signum < 0 && (exponent & 1) == 1 ? -1 : 1);
    int[] baseToPow2 = this.mag;
    int[] result = { 1 };
    while (exponent != 0) {
        if ((exponent & 1) == 1) {
            result = multiplyToLen(result, result.length, baseToPow2, baseToPow2.length, null);
            result = trustedStripLeadingZeroInts(result);
        }
        if ((exponent >>>= 1) != 0) {
            baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
            baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
        }
    }
    return new BigInteger(result, newSign);
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.MutableBigInteger.modInverseMP2(int)

MutableBigInteger modInverseMP2(int k) {
    if (isEven()) throw new ArithmeticException('Non-invertible. (GCD != 1)');
    if (k > 64) return euclidModInverse(k);
    int t = inverseMod32(value[offset + intLen - 1]);
    if (k < 33) {
        t = (k == 32 ? t : t & ((1 << k) - 1));
        return new MutableBigInteger(t);
    }
    long pLong = (value[offset + intLen - 1] & LONG_MASK);
    if (intLen > 1) pLong |= ((long) value[offset + intLen - 2] << 32);
    long tLong = t & LONG_MASK;
    tLong = tLong * (2 - pLong * tLong);
    tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));
    MutableBigInteger result = new MutableBigInteger(new int[2]);
    result.value[0] = (int) (tLong >>> 32);
    result.value[1] = (int) tLong;
    result.intLen = 2;
    result.normalize();
    return result;
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.checkScale(long)

/**
     * Check a scale for Underflow or Overflow.  If this BigDecimal is
     * uninitialized or initialized and nonzero, throw an exception if
     * the scale is out of range.  If this is zero, saturate the scale
     * to the extreme value of the right sign if the scale is out of
     * range.
     * @param val The new scale.
     * @throws ArithmeticException (overflow or underflow) if the new
     *         scale is out of range.
     * @return validated scale as an int.
     */
private int checkScale(long val) {
    if ((int) val != val) {
        if ((this.intCompact != INFLATED && this.intCompact != 0) || (this.intVal != null && this.signum() != 0) || (this.intVal == null && this.intCompact == INFLATED)) {
            if (val > Integer.MAX_VALUE) throw new ArithmeticException('Underflow');
            if (val < Integer.MIN_VALUE) throw new ArithmeticException('Overflow');
        } else {
            return (val > Integer.MAX_VALUE) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
    }
    return (int) val;
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.divide(BigDecimal, int, int)

/**
     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
     * divisor)</tt>, and whose scale is as specified.  If rounding must
     * be performed to generate a result with the specified scale, the
     * specified rounding mode is applied.
     * The new {@link #divide(BigDecimal, int, RoundingMode)} method
     * should be used in preference to this legacy method.
     * @param  divisor value by which this <tt>BigDecimal</tt> is to be divided.
     * @param  scale scale of the <tt>BigDecimal</tt> quotient to be returned.
     * @param  roundingMode rounding mode to apply.
     * @return <tt>this / divisor</tt>
     * @throws ArithmeticException if <tt>divisor</tt> is zero,
     *         <tt>roundingMode==ROUND_UNNECESSARY</tt> and
     *         the specified scale is insufficient to represent the result
     *         of the division exactly.
     * @throws IllegalArgumentException if <tt>roundingMode</tt> does not
     *         represent a valid rounding mode.
     * @see    #ROUND_UP
     * @see    #ROUND_DOWN
     * @see    #ROUND_CEILING
     * @see    #ROUND_FLOOR
     * @see    #ROUND_HALF_UP
     * @see    #ROUND_HALF_DOWN
     * @see    #ROUND_HALF_EVEN
     * @see    #ROUND_UNNECESSARY
     */
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
    if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) throw new IllegalArgumentException('Invalid rounding mode');
    BigDecimal dividend;
    if (checkScale((long) scale + divisor.scale) >= this.scale) {
        dividend = this.setScale(scale + divisor.scale);
    } else {
        dividend = this;
        divisor = divisor.setScale(checkScale((long) this.scale - scale));
    }
    boolean compact = dividend.intCompact != INFLATED && divisor.intCompact != INFLATED;
    long div = INFLATED;
    long rem = INFLATED;
    ;
    BigInteger q = null, r = null;
    if (compact) {
        div = dividend.intCompact / divisor.intCompact;
        rem = dividend.intCompact % divisor.intCompact;
    } else {
        BigInteger i[] = dividend.inflate().intVal.divideAndRemainder(divisor.inflate().intVal);
        q = i[0];
        r = i[1];
    }
    if (compact) {
        if (rem == 0) return new BigDecimal(div, scale);
    } else {
        if (r.signum() == 0) return new BigDecimal(q, scale);
    }
    if (roundingMode == ROUND_UNNECESSARY) throw new ArithmeticException('Rounding necessary');
    int signum = dividend.signum() * divisor.signum();
    boolean increment;
    if (roundingMode == ROUND_UP) {
        increment = true;
    } else if (roundingMode == ROUND_DOWN) {
        increment = false;
    } else if (roundingMode == ROUND_CEILING) {
        increment = (signum > 0);
    } else if (roundingMode == ROUND_FLOOR) {
        increment = (signum < 0);
    } else {
        int cmpFracHalf;
        if (compact) {
            cmpFracHalf = longCompareTo(Math.abs(2 * rem), Math.abs(divisor.intCompact));
        } else {
            cmpFracHalf = r.add(r).abs().compareTo(divisor.intVal.abs());
        }
        if (cmpFracHalf < 0) {
            increment = false;
        } else if (cmpFracHalf > 0) {
            increment = true;
        } else {
            if (roundingMode == ROUND_HALF_UP) increment = true; else if (roundingMode == ROUND_HALF_DOWN) increment = false; else {
                if (compact) increment = (div & 1L) != 0L; else increment = q.testBit(0);
            }
        }
    }
    if (compact) {
        if (increment) div += signum;
        return new BigDecimal(div, scale);
    } else {
        return (increment ? new BigDecimal(q.add(BigInteger.valueOf(signum)), scale) : new BigDecimal(q, scale));
    }
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigDecimal.longValueExact()

/**
     * Converts this <tt>BigDecimal</tt> to a <tt>long</tt>, checking
     * for lost information.  If this <tt>BigDecimal</tt> has a
     * nonzero fractional part or is out of the possible range for a
     * <tt>long</tt> result then an <tt>ArithmeticException</tt> is
     * thrown.
     * @return this <tt>BigDecimal</tt> converted to a <tt>long</tt>.
     * @throws ArithmeticException if <tt>this</tt> has a nonzero
     *         fractional part, or will not fit in a <tt>long</tt>.
     * @since  1.5
     */
public long longValueExact() {
    if (intCompact != INFLATED && scale == 0) return intCompact;
    if ((precision() - scale) > 19) throw new java.lang.ArithmeticException('Overflow');
    if (this.signum() == 0) return 0;
    if ((this.precision() - this.scale) <= 0) throw new ArithmeticException('Rounding necessary');
    BigDecimal num = this.setScale(0, ROUND_UNNECESSARY).inflate();
    if (num.precision() >= 19) {
        if (LONGMIN == null) {
            LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
            LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
        }
        if ((num.intVal.compareTo(LONGMIN) < 0) || (num.intVal.compareTo(LONGMAX) > 0)) throw new java.lang.ArithmeticException('Overflow');
    }
    return num.intVal.longValue();
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.probablePrime(int, Random)

/**
     * Returns a positive BigInteger that is probably prime, with the
     * specified bitLength. The probability that a BigInteger returned
     * by this method is composite does not exceed 2<sup>-100</sup>.
     * @param  bitLength bitLength of the returned BigInteger.
     * @param  rnd source of random bits used to select candidates to be
     *        tested for primality.
     * @return a BigInteger of <tt>bitLength</tt> bits that is probably prime
     * @throws ArithmeticException <tt>bitLength < 2</tt>.
     * @see    #bitLength
     */
public static BigInteger probablePrime(int bitLength, Random rnd) {
    if (bitLength < 2) throw new ArithmeticException('bitLength < 2');
    return (bitLength < SMALL_PRIME_THRESHOLD ? smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) : largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

java.math.BigInteger.nextProbablePrime()

/**
    * Returns the first integer greater than this <code>BigInteger</code> that
    * is probably prime.  The probability that the number returned by this
    * method is composite does not exceed 2<sup>-100</sup>. This method will
    * never skip over a prime when searching: if it returns <tt>p</tt>, there
    * is no prime <tt>q</tt> such that <tt>this < q < p</tt>.
    * @return the first integer greater than this <code>BigInteger</code> that
    *         is probably prime.
    * @throws ArithmeticException <tt>this < 0</tt>.
    * @since 1.5
    */
public BigInteger nextProbablePrime() {
    if (this.signum < 0) throw new ArithmeticException('start < 0: ' + this);
    if ((this.signum == 0) || this.equals(ONE)) return TWO;
    BigInteger result = this.add(ONE);
    if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
        if (!result.testBit(0)) result = result.add(ONE);
        while (true) {
            if (result.bitLength() > 6) {
                long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
                if ((r % 3 == 0) || (r % 5 == 0) || (r % 7 == 0) || (r % 11 == 0) || (r % 13 == 0) || (r % 17 == 0) || (r % 19 == 0) || (r % 23 == 0) || (r % 29 == 0) || (r % 31 == 0) || (r % 37 == 0) || (r % 41 == 0)) {
                    result = result.add(TWO);
                    continue;
                }
            }
            if (result.bitLength() < 4) return result;
            if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY)) return result;
            result = result.add(TWO);
        }
    }
    if (result.testBit(0)) result = result.subtract(ONE);
    int searchLen = (result.bitLength() / 20) * 64;
    while (true) {
        BitSieve searchSieve = new BitSieve(result, searchLen);
        BigInteger candidate = searchSieve.retrieve(result, DEFAULT_PRIME_CERTAINTY);
        if (candidate != null) return candidate;
        result = result.add(BigInteger.valueOf(2 * searchLen));
    }
}

Source: "Java SE Downloads: Java SE 6 JDK Source Code", at: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Comments

Popular posts from this blog

BAD_CERTIFICATE - A corrupt or unuseable certificate...

This is a simple symptom-cause-solution blog entry only. I hope these blogs will help fellow administrators.
Symptom
In wls_utc, when trying to test a webservice using SSL, the following error message is received: javax.net.ssl.SSLKeyException: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable certificate was received.
If SSL debugging is enabled, the following error also appears in the logs: ExecuteThread: '4' for queue: 'weblogic.kernel.Default (self-tuning)' <1254822672320>>
verification failed because RSA key public exponent [3] is too small
Cause
The certificate encryption is of a weaker strength than expected by newer versions of Java.
Solution
Add the flag "-Dweblogic.security.SSL.allowSmallRSAExponent=true" to the server startup parameters.
References


None.

Connection refused: No available router to destination

This is a simple symptom-cause-solution blog entry only. I hope these blogs will help fellow administrators.
Symptom

The following exception occurs in WebLogic server logs. Most likely to occur during WebLogic server start-up, but similar exceptions may occur at other times.
java.net.ConnectException: t3://myserver:8000: Destination unreachable; nested exception is: java.net.ConnectException: Connection refused: connect; No available router to destination] at weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:49) at weblogic.jndi.WLInitialContextFactoryDelegate.toNamingException(WLInitialContextFactoryDelegate.java:773) at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java:363) at weblogic.jndi.Environment.getContext(Environment.java:307) at weblogic.jndi.Environment.getContext(Environment.java:277)
Cause
This message (Connection refused: connect; No available router to destination) is a kind of "catch…

BEASVC.EXE - WebLogic as a Windows Service

I remember the first time I had to work out why WebLogic wouldn't run as a service. It was a frustrating experience. There were no error messages. No Windows error dialog. No console output.

How do you troubleshoot something like this??!!

This short article will show you. For simplicity I'll talk about the node manager, but the same principles apply for running an admin or managed server as a service.

First Steps

First, you still have your server logs. Sure the console output is better, but it's a starting point. Check this log for errors and especially take note of the start up variables such as PATH and CLASSPATH. If the server log isn't being created, that tells you WebLogic probably isn't even being started. (Check that you have a license file if you haven't already.)

Ok, so the logs were no help. The next step is to look at how the service is trying to start WebLogic.

When you install WebLogic as a service, you're really setting up beasvc.exe as the service.…