Detailed Explanation of BigInteger Case of Java Handling Super Large Number Types

  • 2021-11-13 01:34:31
  • OfStack

1. Introduction to BigInteger

If 1 integer data exceeds the maximum type length of integer long at the time of operation, the data cannot be loaded, so the BigInteger class should be used for operation at this time. These large numbers are passed in as strings.

Compared with Integer, BigInteger can be described as big. It is used for scientific calculation. Integer can only accommodate one int, so the maximum value is 31 visits of 2 minus 1, and the decimal is 2147483647. However, if you need to calculate a larger number, 31 bits is obviously not enough, so BigInteger can meet our needs at this time.

The number of digits that BigInteger can accommodate is large. I simply tried it for 1 time, and there is no problem with thousands of digits. In addition to its large capacity, BigInteger also encapsulates some common operations, such as the basic operation of */, as well as the operations of absolute value, inverse number, greatest common divisor, prime number and so on.

2. Common functions of BigInteger

BigInteger (String value): Construction method, BigInteger add (BigInteger value): Addition, BigInteger subtract (BigInteger value): Subtraction, BigInteger multiply (BigInteger value): Multiplication, BigInteger divide (BigInteger divisor): Division, BigInteger modInverse (BigInteger m): Modulus, BigInteger pow (int exponent): Power, BigInteger max (BigInteger value): Maximum number, BigInteger min (BigInteger value): Minimum number, BigInteger abs (): Absolute value, BigInteger negate (): The opposite number, int intValue (): Converts int, converts BigInteger type data to int. BigInteger valueOf (long val): Change to BigInteger, change long type to BigIntege type

Sample code

[Title]

Enter an integer n 1 < n < 10^9
Output 1 integer
Find out the sum of all the elements in all the non-empty subsets, then take the modulus of 10 ^ 9 +7 and output the result
For example, input 2 has 3 non-empty subsets of {1}, {2}, {1, 2}, and the sum of all elements is 4
The output is 4

Train of thought

It will definitely exceed with int, and BigInteger is needed
For input n, the sum of all elements is n * 2 ^ (n-1)
Then take the module of 10 7 +7


import java.math.BigInteger;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String n = sc.next();
        BigInteger res = count(new BigInteger(n));
        BigInteger m = BigInteger.valueOf(10).pow(7).add(BigInteger.valueOf(7));
        System.out.println(res.mod(m));;
    }

    //  Calculation formula  n*2^(n-1)
    static BigInteger count(BigInteger n) {
        return n.multiply(BigInteger.valueOf(2).pow(n.intValue()-1));
    }
}


Related articles: