Combination 연산을 최대 100까지의 숫자들을 이용해서 수행하면 금새 Long의 범위마저 넘어선다. 이때 BigInteger 클래스를 사용한다.
일반적으로 int 값을 그대로 대입할 수 없고, valueOf 메서드를 통해 변환해서 넣어야 하며, 연산도 메서드를 통해서 이루어진다.
또한 10C7과 10C3는 결과값은 동일하지만, 반복 연산 횟수에서 각각 7회, 3회로 차이가 난다. 이렇게 연산횟수를 줄여 시간을 절약할 수 있다.
import java.math.BigInteger;
import java.util.Scanner;
public class BJ2407 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, m, i;
BigInteger answer = BigInteger.valueOf(1);
n = sc.nextInt();
m = sc.nextInt();
sc.close();
//반복문 연산횟수를 줄일 수 있음
if (m > n - m) {
m = n - m;
}
for (i = 0; i < m; i++) {
answer = answer.multiply(BigInteger.valueOf(n - i));
answer = answer.divide(BigInteger.valueOf(i + 1));
}
System.out.println(answer);
}
}