SoFunction
Updated on 2025-04-26

One article allows you to thoroughly learn the common operations of Java BigInteger class

The basic concept of BigInteger

1. What is BigInteger

  • BigIntegeryesClasses in the package, specially used to represent integers of arbitrary precision.
  • It solves basic data types (e.g.intlong) accuracy limitation problem. for example:
    • intThe maximum value is 2³¹-1 (2.1 billion).
    • longThe maximum value of  is 2⁶³-1 (approximately 19-bit decimal number).
    • If you need to represent a larger integer, you must useBigInteger

2. Features

  • Immutability
    • BigIntegerIt is an immutable object. Each operation will return a new instance without modifying the original object.
  • Any accuracy
    • It is limited only to the size of available memory, so it can represent super-large integers.
  • Underlying implementation
    • BigIntegerLower layer adoptionint[]Arrays store data, each array element stores a part of the number, and operates through mathematical algorithms.
    • For example, store a very large number separately in a 32-bit segment.

How BigInteger is constructed

Constructor

BigIntegerMultiple constructors are provided for creating instances.

1. Use string constructs

This is the most commonly used constructor, supporting numbers of arbitrary sizes:

BigInteger bigInt = new BigInteger("123456789012345678901234567890");
  • parameter
    • A number represented by a string (supports positive and negative signs).
    • If the string contains illegal characters (such as letters), it will be thrownNumberFormatException

2. Use the conversion of basic data types

Through static methodsWillintorlongConvert toBigInteger

BigInteger bigInt = (123456789L);
  • Notice
    • valueOfMethods only supportlongValues ​​within the range.
    • For larger numbers, string construction is still required.

3. Construct from binary, octal, hexadecimal, etc.

Supports string construction in specified binary:

BigInteger bigInt = new BigInteger("1010", 2); // Binary -> Decimal: 10BigInteger hexInt = new BigInteger("1A", 16); // Hexadecimal -> Decimal: 26

4. Generate random numbers

By constructing a random number:

BigInteger randomBigInt = new BigInteger(50, new Random()); // Generate 50-bit random numbers
  • Parameter meaning
    • The first parameter is the number of bits (bits).
    • The second parameter is the random number generator.

5. Commonly used constants

   // means 0    // means 1    // means 10

Common operations of BigInteger

1. Arithmetic operations

BigInteger a = new BigInteger("12345");
BigInteger b = new BigInteger("67890");

addition

BigInteger sum = (b); // Result: 80235

Subtraction

BigInteger diff = (b); // Result: -55545

multiplication

BigInteger product = (b); // Result: 838102050

division

BigInteger quotient = (a); // Results: 5

Take a model

BigInteger mod = (a); // Result: 12345
  • NoticedivideIt is integer division and will not produce decimal parts.

Mixed operations: addition, multiplication

All operations are chained. For example:

BigInteger result = (b).multiply(a).divide(b);

2. Power operation

  • Normal exponent operation (no modulus):
BigInteger base = new BigInteger("2");
BigInteger result = (10); // 2^10 = 1024
  • Modular exponentiation operation (commonly used in large number operations):
BigInteger base = new BigInteger("2");
BigInteger exp = new BigInteger("10");
BigInteger mod = new BigInteger("7");
BigInteger modPowResult = (exp, mod); // (2^10) % 7 = 2

Underlying optimization:

  • Modular exponentiation operation uses an exponential squared algorithm, with a time complexity of O(log(n)), which is more efficient than stepwise calculation.

3. Comparison and maximum minimum value

Compare sizes

compareToThe method returns the following results:

  • 1: The current object is larger than the comparison object.
  • -1: The current object is smaller than the comparison object.
  • 0: The two are equal.
    Example:
int compare = (b);

Maximum and minimum values

  • Returns the larger or smaller value of the two numbers:
BigInteger max = (b);
BigInteger min = (b);

4. Bit operation

Bitwise operation

  • Bitwise with:
BigInteger result = (b);
  • bitwise or:
BigInteger result = (b);
  • Bitwise XOR:
BigInteger result = (b);

Displacement operation

  • Move left:
BigInteger result = (2); // Move left by 2 digits
  • Move right:
BigInteger result = (2); // Move right 2 digits

5. Mathematical Related

Find the absolute value

BigInteger abs = ();

Find the greatest common divisor

BigInteger gcd = (b); // Returns the greatest common divisor of a and b

Modal inverse elements

The modular inverse element is an integer that satisfies the following formula:

( a × x ) % m = 1 (a \times x) \% m = 1(a×x)%m=1

Code example:

BigInteger modInverse = (mod); // Calculate the modular inverse element of a

Check if it is a prime number

boolean isPrime = (10); // The parameters are the credibility of the test
  • The parameter is an integer. The larger the value, the higher the reliability of the test results.

6. Calculation conversion

  • Convert to string (default decimal):
String decimalStr = ();
  • Convert to other binary representations:
String binaryStr = (2);  // BinaryString hexStr = (16);   // hexadecimal

optimization

1. Immutability

BigIntegerEach operation of  returns a new object. If you need to modify the values ​​frequently, you can consider multiplexing variables to reduce object creation.

2. Pay attention to memory consumption

Extra large integers consume more memory. For example:

BigInteger big = new BigInteger("9".repeat(1000000)); // 100 Ten thousand digits

Summarize

This is the end of this article about the common operations of the BigInteger class in Java. For more related contents of the common operations of the BigInteger class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!