BigInteger (큰 수 다루기)

Yumi Kim·2025년 4월 3일

Java 알고리즘

목록 보기
16/17
post-thumbnail

int와 long의 범위를 넘는 수를 다뤄야할 때!

  • TypeRange
    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제한 없음

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");
addBigInteger result = bigInt1.add(bigInt2);
subtractBigInteger result = bigInt1.subtract(bigInt2);
multiplyBigInteger result = bigInt1.multiply(bigInt2);
divideBigInteger result = bigInt1.divide(bigInt2);
remainderBigInteger result = bigInt1.remainder(bigInt2);
compareToint comparisonResult = bigInt1.compareTo(bigInt2);
absBigInteger result = bigInt.abs();
bitLength 비트 길이int bitLength = bigInt.bitLength();
toString(2) 이진수 변환String binary = bigInt.toString(2);
isProbablePrime 소수 확인boolean isPrime = bigInt.isProbablePrime(10);
profile
✿.。.:* ☆:**:. 🎀 Daily Study 🎀 .:**:.☆*.:。.✿

0개의 댓글