티스토리 뷰

728x90
반응형

자바의 기본 자료형인 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 (약 900경)

long 타입으로도 충분히 큰 수를 저장할 수 있지만,

 

가끔 알고리즘 문제에서 이 범위를 넘는 수의 연산이 필요해질 때가 있다.

 

그럴 때 사용하는 것이 범위의 제한이 없는 자료형, BigInteger다.

 

추가로 BigInteger는 java.math 패키지에 소속되어 있으며, 사용 시 아래와 같이 import 해주어야 한다.

import java.math.BigInteger;

 

선언

 

BigInteger 자료형을 선언하는 방법은 크게 세 가지가 있다.

import java.math.BigInteger;

public class BigIntegerPractice {
    public static void main(String[] args) {

        BigInteger a = BigInteger.valueOf(100); // 정수로 생성
        BigInteger b = new BigInteger("100"); // 문자열로 생성
        BigInteger c = new BigInteger("100", 2); // 2진법으로 생성

        System.out.println(a + "\n" + b + "\n" + c);
    }
}
100
100
4

여기서 주의할 점은, BigInteger.valueOf()를 이용해 수를 저장할 때 int범위가 넘어가면

 

반드시 숫자 뒤에 L을 붙여줘야 한다는 것이다.

 

문자열로 생성할 때는 제한이 없다.

BigInteger a = BigInteger.valueOf(2147483648); // 에러
BigInteger a2 = BigInteger.valueOf(2147483648L); // 통과
BigInteger b = new BigInteger("2147483648"); // 통과

또한 재미있게도 BigInteger.valueOf()엔 long 범위를 넘어서는 수는 입력이 불가능한데,

 

에러가 나거나 오버플로우 되어서 처음으로 돌아가게 된다.

BigInteger a = BigInteger.valueOf(9223372036854775808L); // 에러
BigInteger a2 = BigInteger.valueOf(9223372036854775807L); // 통과
BigInteger a3 = BigInteger.valueOf(9223372036854775807L + 1); // 통과, -9223372036854775808 출력

하지만 웃기게도 일단 수를 생성한 후 더하면 이 문제에서 자유로운데,

BigInteger a2 = BigInteger.valueOf(9223372036854775807L); // 통과
BigInteger a3 = BigInteger.valueOf(9223372036854775807L + 1); // 통과, -9223372036854775808 출력
BigInteger a4 = a2.add(BigInteger.valueOf(1)); // 통과, 9223372036854775808 출력

어쨌거나 BigInteger를 사용해야 할 때는 문자열 객체로 생성하는 것이 정신건강에 이롭다.

 

각종 연산

 

사칙연산을 포함한 몇 가지 연산에 대해서 알아보자.

 

직접 사용해보면 알겠지만 워낙 다루는 수가 크다보니 기본형에 비해 연산 속도는 느리다.

import java.math.BigInteger;

public class BigIntegerPractice {
    public static void main(String[] args) {

        BigInteger a = new BigInteger("100");
        BigInteger b = new BigInteger("200");

        BigInteger bigAdd = a.add((BigInteger.valueOf(10))); // 숫자 더하기
        BigInteger bigAdd2 = a.add(b); // 객체끼리 더하기
        BigInteger bigSub = a.subtract(b); // 빼기
        BigInteger bigMulti = a.multiply(b); // 곱하기
        BigInteger bigDiv = a.divide(b); // 나누기
        BigInteger bigRem = a.remainder(b); // 나머지
        BigInteger bigPow = a.pow(b.intValue()); // 거듭제곱. 지수에는 0 부터 Integer.Max_Value 까지 허용
        BigInteger bigSqrt = a.sqrt(); // 제곱근
        int bigCompare = a.compareTo(b); // 대소비교. 클 경우 1, 같을 경우 0, 작을 경우 -1
        int bigBit = a.bitCount(); // 2진수로 변경했을 때의 비트 수
        BigInteger bigMax = a.max(b); // 대소비교 후 큰 값 출력
        BigInteger bigMin = a.min(b); // 대소비교 후 작은 값 출력
        String bigStr = a.toString(); // 문자열로 변경
        String bigByte = a.toString(2); // 2진수로 변경

    }
}
bigAdd = 110
bigAdd2 = 300
bigSub = -100
bigMulti = 20000
bigDiv = 0
bigRem = 100
bigPow = 100000000000000...[생략]
bigSqrt = 10
bigCompare = -1
bigBit = 3
bigMax = 200
bigMin = 100
bigStr = 100
bigByte = 1100100

 

위에 사용한 메서드를 요약하면 아래와 같다.

 

Return Type Method Description
BigInteger add() 더하기
BigInteger subtract() 빼기
BigInteger multiply() 곱하기
BigInteger divide() 나누기
BigInteger remainder() a b로 나눈 나머지
BigInteger pow() 거듭제곱
BigInteger sqrt() 제곱근
int compareTo() 대소비교 후 클 경우 1, 같을 경우 0, 작을 경우 -1
int bitcount() 이진수로 변경했을 때의 비트 수
BigInteger max() 대소비교 후 큰 값 출력
BigInteger min() 대소비교 후 작은 값 출력
String toString() 문자열로 변환
String toString(2) 이진수로 변환 후 문자별로 저장

 

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함