BigInteger
-Java에서 매우 큰 정수를 다루기 위해 제공되는 클래스
-java.math 패키지에서 BigInteger 클래스를 제공
-이론적으로 메모리가 허용하는 한 무한대의 정수 다룰 수 있음
BigInteger의 특징
-불변성(Immutable): BigInteger 객체는 한 번 생성되면 그 값을 변경할 수 없음, 연산 결과는 새로운 BigInteger 객체로 반환
-다양한 연산 지원: 사칙연산뿐만 아니라 모듈러 연산, 비트 연산 등 다양한 연산을 지원
1. 선언 및 초기화
import java.math.BigInteger;
BigInteger bigNumber = new BigInteger("12345678901234567890");
// long 값 기반 생성, valueOf 메서드 사용
BigInteger bigNumber = BigInteger.valueOf(1234567890L);
2. 사칙연산
BigInteger a = new BigInteger("10000000000000000000");
BigInteger b = new BigInteger("20000000000000000000");
BigInteger sum = a.add(b); // 덧셈
BigInteger diff = a.subtract(b); // 뺄셈
BigInteger product = a.multiply(b); // 곱셈
BigInteger quotient = a.divide(b); // 나눗셈
BigInteger remainder = a.remainder(b); // 나머지
3. 비교 연산 : compareTo 메서드
int result = a.compareTo(b);
if (result == 0) {
System.out.println("a와 b는 같습니다.");
} else if (result < 0) {
System.out.println("a는 b보다 작습니다.");
} else {
System.out.println("a는 b보다 큽니다.");
}
4. 형 변환 : 기본데이터타입으로 변환 위해서 해당 타입의 value 메서드 사용
BigInteger bigNumber = new BigInteger("12345");
int intValue = bigNumber.intValue();
long longValue = bigNumber.longValue();
float floatValue = bigNumber.floatValue();
double doubleValue = bigNumber.doubleValue();
5. 추가적인 연산들
// 거듭제곱
BigInteger base = new BigInteger("2");
BigInteger result = base.pow(10); // 2의 10제곱
// 최대공약수
BigInteger a = new BigInteger("48");
BigInteger b = new BigInteger("18");
BigInteger gcd = a.gcd(b); // 결과는 6
// 소수 판정 및 소수 생성
BigInteger prime = BigInteger.probablePrime(100, new Random());
boolean isPrime = prime.isProbablePrime(100);
정렬 방법들
// 배열 정렬 방법들
Arrays.sort();
Arrays.parallelSort();
// 리스트, 벡터 등의 정렬
Collections.sort();
// Stream 정렬
stream.sorted();
'Bootcamp > java codingtest' 카테고리의 다른 글
최소 신장 트리 MST (0) | 2025.04.22 |
---|---|
동적 계획법, JAVA 자료형 (1) | 2025.04.21 |
BigDecimal, Comparator 인터페이스 (0) | 2025.04.20 |
문자열 리스트, array (0) | 2025.04.14 |
재귀 (0) | 2025.04.12 |