프로그래밍언어/Java

[Java] 큰 숫자를 다루기 위한 BigInteger 개념 및 사용 방법

멍토 2024. 4. 4.

BigInteger 소개

자바의 BigInteger 클래스는 제한 없이 큰 정수를 다룰 수 있는 기능을 제공한다. 이 클래스는 일반적인 정수 자료형으로는 처리할 수 없는 매우 큰 수를 다룰 때 사용되며, java.math 패키지에 속해 있다. BigInteger는 암호화, 금융 계산, 수학적 연산 등 다양한 분야에서 유용하게 사용된다.

BigInteger의 주요 메서드

BigInteger는 불변 객체로, 각종 수학적 연산 후 새로운 BigInteger 인스턴스를 반환한다. 주요 메서드로는 add(), subtract(), multiply(), divide(), mod() 등이 있다. 이 클래스는 문자열이나 byte 배열로부터 BigInteger 객체를 생성할 수 있는 생성자도 제공한다.

사칙연산 예제


import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger num1 = new BigInteger("30");
        BigInteger num2 = new BigInteger("12");

        BigInteger sum = num1.add(num2);
        BigInteger difference = num1.subtract(num2);
        BigInteger product = num1.multiply(num2);
        BigInteger quotient = num1.divide(num2);

        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
        System.out.println("Product: " + product);
        System.out.println("Quotient: " + quotient);
    }
}
        

자료형 변환 예제


import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger bigInt = new BigInteger("123456789");

        long longValue = bigInt.longValue();
        int intValue = bigInt.intValue();
        double doubleValue = bigInt.doubleValue();
        float floatValue = bigInt.floatValue();
        String stringValue = bigInt.toString();

        System.out.println("Long value: " + longValue);
        System.out.println("Int value: " + intValue);
        System.out.println("Double value: " + doubleValue);
        System.out.println("Float value: " + floatValue);
        System.out.println("String value: " + stringValue);
    }
}
        

BigInteger 비교 예제


import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger num1 = new BigInteger("123456789");
        BigInteger num2 = new BigInteger("987654321");

        if (num1.compareTo(num2) > 0) {
            System.out.println(num1 + " is greater than " + num2);
        } else if (num1.compareTo(num2) < 0) {
            System.out.println(num1 + " is less than " + num2);
        } else {
            System.out.println(num1 + " and " + num2 + " are equal");
        }
    }
}
        

소수 판별 기능 사용 예제


import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger bigInt = new BigInteger("12345678910111213141516171819202122232425");

        boolean isPrime = bigInt.isProbablePrime(10);

        if (isPrime) {
            System.out.println(bigInt + " is probably prime.");
        } else {
            System.out.println(bigInt + " is not prime.");
        }
    }
}
        

장단점 분석

BigInteger는 큰 수를 다루는 데 있어 뛰어난 유연성을 제공하지만, 기본 자료형에 비해 처리 속도가 느리고 메모리 사용량이 더 많다는 단점이 있다. 따라서 상황에 따라 적절히 사용하는 것이 중요하다.

댓글

💲 광고입니다.