Java BigInteger Calculate square(BigInteger x)

Here you can find the source of square(BigInteger x)

Description

square

License

Open Source License

Declaration

static BigInteger square(BigInteger x) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.math.BigInteger;

public class Main {
    static BigInteger square(BigInteger x) {
        final int bitLength = x.bitLength();
        if (bitLength < 1800) {
            return x.multiply(x);
        }//from w ww  .  j a v a 2s . c om
        if (x.signum() < 0) {
            x = x.negate();
        }
        final int n = addInts(bitLength, 1) / 2;
        final BigInteger u1 = x.shiftRight(n);
        final BigInteger u0 = x.subtract(u1.shiftLeft(n));
        final BigInteger v = u0.subtract(u1);
        final BigInteger t2 = square(u1);
        final BigInteger t1 = square(v);
        final BigInteger t0 = square(u0);
        return t2.shiftLeft(2 * n).add(t2.shiftLeft(n)).subtract(t1.shiftLeft(n)).add(t0.shiftLeft(n)).add(t0);
    }

    static BigInteger multiply(BigInteger x, BigInteger y) {
        final int bitLengthX = x.bitLength();
        final int bitLengthY = y.bitLength();
        if (bitLengthX <= 256 || bitLengthY <= 256 || addInts(bitLengthX, bitLengthY) <= 3600) {
            return x.multiply(y);
        }
        return x.multiply(y);
    }

    public static int addInts(int a, int b) {
        if ((a > 0 && b > Integer.MAX_VALUE - a) || (a < 0 && b < Integer.MIN_VALUE - a)) {
            throw new ArithmeticException("int \"+\" overflow");
        }
        return a + b;
    }
}

Related

  1. splitBigInt(BigInteger value, int n)
  2. splitFloat(BigInteger rawFloat, int signWidth, int exponentWidth, int mantissaWidth)
  3. sqrt(BigInteger n)
  4. sqrt(BigInteger n)
  5. sqrt(BigInteger n)
  6. subArray(BigInteger[] input, int start, int end)
  7. substring(final String lhs, final BigInteger _start, final BigInteger _end)
  8. sum(BigInteger valueA, BigInteger valueB)
  9. sum(BigInteger... values)