
int와 long의 범위를 넘는 수를 다뤄야할 때!
Type Range int -2,147,483,648 ~ 2,147,483,647 (약 21억) long -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 BigInteger 제한 없음
java.math.BigInteger 클래스를 사용import java.math.BigInteger;
BigInteger는 기본 데이터 타입처럼 직접 선언할 수 없으며, 문자열로 생성하거나 BigInteger.valueOf() 메서드를 사용하여 생성
// 문자열로 생성
BigInteger b = new BigInteger("100");
// 정수로 생성 (int 범위를 넘어가면 L을 붙여야 함)
BigInteger a = BigInteger.valueOf(100);
// 2진수로 생성
BigInteger c = new BigInteger("100", 2);
BigInteger는 기본 연산자(+, -, *, / 등)를 사용할 수 없으며, 메서드를 통해 연산
| 함수명 | 예시 코드 |
|---|---|
| BigInteger 생성 | BigInteger bigInt = new BigInteger("123456789012345678901234567890"); |
| add | BigInteger result = bigInt1.add(bigInt2); |
| subtract | BigInteger result = bigInt1.subtract(bigInt2); |
| multiply | BigInteger result = bigInt1.multiply(bigInt2); |
| divide | BigInteger result = bigInt1.divide(bigInt2); |
| remainder | BigInteger result = bigInt1.remainder(bigInt2); |
| compareTo | int comparisonResult = bigInt1.compareTo(bigInt2); |
| abs | BigInteger result = bigInt.abs(); |
| bitLength 비트 길이 | int bitLength = bigInt.bitLength(); |
| toString(2) 이진수 변환 | String binary = bigInt.toString(2); |
| isProbablePrime 소수 확인 | boolean isPrime = bigInt.isProbablePrime(10); |