본문 바로가기
Today I Learned/Java

[Java] long 범위보다 큰 정수를 사칙연산하기: BigInteger

by 프로그래 밍구 2023. 11. 10.

BigInteger

 int, double, long 자료형 중에서 가장 범위가 넓은 long의 범위는 -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807이다. 만약 long의 범위를 초과하는 수를 다룰 때는 BigInteger 클래스를 사용할 수 있다.

 BigInteger는 문자열로 표현된 숫자를 입력받아 객체를 생성한다. 이후 사칙연산을 수행하는 각 메서드를 호출하여 다음과 같이 활용할 수 있다.

 

import java.math.BigInteger;

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

        String a = "12938475029384752983749875";
        String b = "2398475983745983745";

        BigInteger bigIntegerA = new BigInteger(a);
        BigInteger bigIntegerB = new BigInteger(b);

        System.out.println("덧셈 결과 : " + bigIntegerA.add(bigIntegerB));
        System.out.println("뺄셈 결과 : " + bigIntegerA.subtract(bigIntegerB));
        System.out.println("곱셈 결과 : " + bigIntegerA.multiply(bigIntegerB));
        System.out.println("나눗셈 결과 : " + bigIntegerA.divide(bigIntegerB));
        System.out.println("나머지 결과 : " + bigIntegerA.remainder(bigIntegerB));
    }
}

// 덧셈 결과 : 12938477427860736729733620
// 뺄셈 결과 : 12938472630908769237766130
// 곱셈 결과 : 31032621624276441354921087543469780895781875
// 나눗셈 결과 : 5394456
// 나머지 결과 : 1868010328494632155

 

댓글