poj2249 Binomial Showdown——组合数

题目描述
In how many ways can you choose k elements out of n elements, not taking order into account?
Write a program to compute this number.
输入
The input will contain one or more test cases.
Each test case consists of one line containing two integers n (n>=1) and k (0<=k<=n).
Input is terminated by two zeroes for n and k.
输出
For each test case, print one line containing the required number. This number will always fit into an integer, i.e. it will be less than 2 31.
Warning: Don’t underestimate the problem. The result will fit into an integer - but if all intermediate results arising during the computation will also fit into an integer depends on your algorithm. The test cases will go to the limit.
样例输入
4 2
10 5
49 6
0 0
样例输出
6
252
13983816

题意
给定 n,m,求 C(n,m),多组数据

题解
公式 C(n,m)=(n-m+1)*C(n,m-1)/m
直接做会 TLE,我们可以加一个优化
当 n-m

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
long long n,m,ans;
int main(){
    while(~scanf("%lld%lld",&n,&m)){
        ans=1;
        if(!n&&!m) return 0;
        if(n-m<m) m=n-m;
        for(int i=1;i<=m;i++)
            ans=ans*(n-i+1)/i;
        printf("%lld\n",ans);}
}

猜你喜欢

转载自blog.csdn.net/chm_wt/article/details/81461995