时间限制: 1Sec 内存限制: 128MB
题目描述:(原题链接)
组合数的计算虽说简单但也不乏有些陷阱,这主要是因为语言中的数据类型在表示范围上是有限的。更何况还有中间结果溢出的现象,所以千万要小心。
输入:
求组合数的数据都是成对(M与N)出现的,每对整数M和N满足0<m, n≤20,以EOF结束。
样例输入:
5 2
18 13
输出:
输出该组合数。每个组合数换行。
样例输出 :
10
8568
解题思路:
由于结果可能很大,所以采用的是BigInteger处理
注意事项:
注意类型转换
参考代码:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
private static void fab(int n,int m) {
BigInteger nj=BigInteger.ONE,mj=BigInteger.ONE,nmj=BigInteger.ONE;
for(BigInteger i=BigInteger.ONE;i.compareTo(BigInteger.valueOf(n))<=0;i=i.add(BigInteger.ONE)) {
nj=nj.multiply(i);
}
for(BigInteger i=BigInteger.ONE;i.compareTo(BigInteger.valueOf(m))<=0;i=i.add(BigInteger.ONE)) {
mj=mj.multiply(i);
}
for(BigInteger i=BigInteger.ONE;i.compareTo(BigInteger.valueOf(n-m))<=0;i=i.add(BigInteger.ONE)) {
nmj=nmj.multiply(i);
}
BigInteger res =nj.divide(mj.multiply(nmj));
System.out.println(res);
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
while(in.hasNext()) {
int m=in.nextInt(),n=in.nextInt();
fab(m,n);
}
in.close();
}
}