BigInteger Exact Modular Arithmetic

Go beyond long with BigInteger: modPow for exponentiation, modInverse for modular inverses, and factorials that overflow primitive types at 21!.

JavaData Integrity

Code

snippet
import java.math.BigInteger;
import java.security.SecureRandom;

public class ModularMath {

    public static void main(String[] args) {
        // long 最多存到 20!,21! 就溢出;BigInteger 没有上限
        BigInteger factorial = BigInteger.ONE;
        for (int i = 2; i <= 25; i++) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.println("25! = " + factorial);

        // 模幂运算:RSA 与 Diffie-Hellman 的核心步骤
        BigInteger modulus = BigInteger.valueOf(1_000_000_007L);
        System.out.println("7^1024 mod p = "
                + BigInteger.valueOf(7).modPow(BigInteger.valueOf(1024), modulus));

        // 模逆元:a * a^-1 ≡ 1 (mod p),要求 gcd(a, p) = 1
        BigInteger a = BigInteger.valueOf(17);
        BigInteger inverse = a.modInverse(modulus);
        System.out.println("verify inverse: " + a.multiply(inverse).mod(modulus));

        // 概率素性检测:certainty 越大误判概率越低
        BigInteger prime = BigInteger.probablePrime(64, new SecureRandom());
        System.out.println("64-bit probable prime: " + prime);
        System.out.println("is prime: " + prime.isProbablePrime(100));
    }
}

How the snippet works

BigInteger Exact Modular Arithmetic is built around the class ModularMath and the function main.

Repetition is confined to for (int i = 2; i <= 25; i++) — the rest of the file is straight-line.

Applying it

Output lines are prefixed (25! =, 7^1024 mod p =, verify inverse:), so the step behind each printed line stays identifiable.

Statements that matter

BigInteger prime = BigInteger.probablePrime(64, new SecureRandom());
BigInteger modulus = BigInteger.valueOf(1_000_000_007L);
factorial = factorial.multiply(BigInteger.valueOf(i));

Interactive Tools for This Topic

FAQ

What does BigInteger Exact Modular Arithmetic print when run?
Run it as a complete program — the output lines carry labels such as `25! =`, `7^1024 mod p =`, `verify inverse:`.