Java core classes --BigInteger

In Java, the range of the maximum 64-bit signed integer type long int native CPU provided.
It can be calculated directly by using CPU instructions long integer type, very fast.

If we use an integer range than long how to do?
java.math.BigInteger is used to represent an integer of arbitrary size.
With an internal BigInteger int [] array to simulate a very large integers.

BigInteger bi = new BigInteger("12334567890");
System.out.println(bi.pow(5));  //285508931350653308728472814534367643427048294900000

BigInteger made of operation when only an instance method, for example: addition operation;

public class catchExample2 {
    public static void main(String[] args) {
        BigInteger b1 = new BigInteger("12334567890");
        BigInteger b2 = new BigInteger("123123131");
        BigInteger sum = b1.add(b2);
        System.out.println(sum);  //12457691021
    }
}

Ratio and long type integer arithmetic, there will be a BigInteger restricted range, but the disadvantage is slower.
May be converted to an long BigInteger:

public class catchExample2 {
    public static void main(String[] args) {
        BigInteger b1 = new BigInteger("12334567890");
        System.out.println(b1.longValue());
        System.out.println(b1.multiply(b1).longValueExact());  // java.lang.ArithmeticException: BigInteger out of long range
    }
}

When using longValueExact () method, if beyond the type of long range throws ArithmeticException.

BigInteger and Integer, as long, is immutable class, and also inherited from the Number class,
because Number defines converted into several basic types of methods:
  • convert byte: byteValue ()
  • convert Short: shortValue ()
  • Conversion as int: intValue ()
  • convert Long: longValue in ()
  • convert a float: o floatValue ()
  • converted to double: doubleValue ()
Thus, by the method described above, can be converted into a substantially BigInteger type.
If BigInteger range indicated beyond the scope of basic types of information will be lost when the high conversion, that result is not necessarily accurate.
For precise into basic types, may be used inValueExact (), longValueExact () method and the like.
If out of range when converting the direct throw ArithmeticExecption exception.

Guess you like

Origin www.cnblogs.com/yangmingxianshen/p/12501455.html