简体   繁体   中英

Square Root and ++ Operators for BigInteger and BigDecimal

Is there any ready-made Java library for operations over BigInteger and BigDecimal objects?

I'd like to use square root and ++ operators.

Thank you

PS BigInteger.add() should be used instead of ++, I got it. What about square root from BigInteger?

BigInteger is immutable . That makes something like the ++ -operator on it conceptually impossible. You can not change the value of a given BigInteger , just like you can't do it with String .

Incrementing

You always have to create a new BigInteger that holds the incremented value (you can then of course store the reference to that BigInteger in the same variable).

Edit: As pointed out in the comment, "incrementing" would look like:

BigInteger result = a.add(BigInteger.ONE);

or

a = a.add(BigInteger.ONE);

Note that both lines do not change the value of the BigInteger which a originally points to. The last line creates a new BigInteger and stores the reference to it in a .

Calculating the Square

You can calculate the square of a BigInteger like this:

BigInteger a = BigInteger.valueOf(2);
BigInteger a_square = a.multiply(a); // a^2 == a * a

or

BigInteger a_square = a.pow(2);

Square Root

The code is taken from https://gist.github.com/JochemKuijpers/cd1ad9ec23d6d90959c549de5892d6cb . It uses simple bisection and a clever upper bound. Note that a.shiftRight(x) is equivalent to a / 2^x (only for non-negative numbers, but that is all we deal with, anyway)

BigInteger sqrt(BigInteger n) {
    BigInteger a = BigInteger.ONE;
    BigInteger b = n.shiftRight(5).add(BigInteger.valueOf(8));
    while (b.compareTo(a) >= 0) {
        BigInteger mid = a.add(b).shiftRight(1);
        if (mid.multiply(mid).compareTo(n) > 0) {
            b = mid.subtract(BigInteger.ONE);
        } else {
            a = mid.add(BigInteger.ONE);
        }
    }
    return a.subtract(BigInteger.ONE);
}

Using Operators Instead of Methods

Operator overloading like in C++ is not possible in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM