728x90
BigInteger란?
BigInteger는 자바에서 제공하는 클래스 중 하나로, 기본 정수형 int와 long의 범위를 넘어서는 정수를 표현할 수 있는 자료형입니다. BigInteger는 java.math 패키지에 포함되어 있으며, 매우 큰 정수뿐만 아니라 부동소수점 오차를 처리하는 데에도 유용하게 사용될 수 있습니다.
언제 사용할까?
- 범위 확장 : long 자료형으로 표현할 수 없는 큰 수를 다룰 수 있습니다. (long의 최대값은 9223372036854775807)
- 부동소수점 오차 처리 : 실수 연산에서 발생하는 부동소수점 오차를 해결하기 위해 BigDecimal과 함께 사용되는 경우가 많습니다. BidDecimal은 고정 소수점 연산을 하여 부동소수점 오류를 방지할 수 있습니다.
사용 예제
import java.math.BigInteger;
public class BigIntegerExample {
public static void main(String[] args) {
BigInteger bigInt1 = new BigInteger("1234567890123456789012345678901234567890");
BigInteger bigInt2 = new BigInteger("9876543210987654321098765432109876543210");
// 사칙연산
BigInteger sum = bigInt1.add(bigInt2);
BigInteger difference = bigInt1.subtract(bigInt2);
BigInteger product = bigInt1.multiply(bigInt2);
BigInteger quotient = bigInt1.divide(bigInt2);
// 결과 출력
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
}
}
BigInteger 비교 연산
BigInteger는 compareTo() 메소드를 사용하여 두 객체를 비교할 수 있습니다.
import java.math.BigInteger;
public class BigIntegerOperations {
public static void main(String[] args) {
BigInteger bi1 = new BigInteger("10");
BigInteger bi2 = new BigInteger("1000000");
// 비교 연산
System.out.println("Compare bi1 with bi2: " + bi1.compareTo(bi2));
System.out.println("Compare bi2 with bi1: " + bi2.compareTo(bi1));
System.out.println("Compare bi1 with bi1: " + bi1.compareTo(bi1));
}
}
반환 값:
- 0: 두 값이 동일할 때
- 1: 비교된 객체가 더 클 때
- -1: 비교된 객체가 더 작을 때
BigInteger 사용 시 주의사항
- 속도: BigInteger는 내부적으로 큰 숫자를 관리하기 때문에, 연산 속도가 int나 long보다 느립니다. 따라서 큰 숫자 연산이 자주 필요한 경우 성능에 영향을 미칠 수 있습니다.
- 메모리 사용량: BigInteger는 int나 long과 비교해 더 많은 메모리를 사용합니다. 매우 큰 숫자를 다루는 경우 메모리 관리에 유의해야 합니다.
728x90
'Java' 카테고리의 다른 글
[Java] Queue 구현 (1) | 2025.02.10 |
---|---|
[Java] Deque 구현 (1) | 2025.02.04 |
[Java] Stack 구현하기 (1) | 2025.02.01 |
[Java] 실행 시간 측정 (2) | 2025.02.01 |
[Java] SinglyLinkedList 구현 (1) | 2025.01.27 |