使用公式n!/ r!*(nr)!计算二项式系数(c(n,r)或nCr)。以下是Java程序,找出给定整数的二项式系数。
import java.util.Scanner; public class BinomialCoefficient { public static long fact(int i) { if(i <= 1) { return 1; } return i * fact(i - 1); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("输入n值: "); int n = sc.nextInt(); System.out.println("输入r值: "); int r = sc.nextInt(); long ncr = fact(n)/(fact(r)*fact(n-r)); System.out.println("c("+n+", "+r+") :"+ ncr); } }
输出结果
输入n值: 8 输入r值: 3 c(8, 3) :56