Binomial Showdown

时间:2023-03-08 22:37:54
Binomial Showdown

Binomial Showdown

TimeLimit: 1 Second   MemoryLimit: 32 Megabyte

Totalsubmit: 2323   Accepted: 572

Description

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.

Input

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.

Output

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.

Sample Input

4 2
10 5
49 6
0 0

Sample Output

6
252
13983816

题意:实际上就是计算一个组合数C(n,m),但不能根据高中的公式直接进行计算,因为数据增长速度很快,测试数据很大,会爆的,所以应根据原有公式就行优化,边算边除,这样就可以了

代码很简单,关键是思想,这点很重要,没有好的思想和算法是想不出优秀代码的。

另外这题还可以用杨辉三角或其变形来做,思路都是用递推公式

#include<stdio.h>
longlong sum;
int main()
{
int k,n,m;
while(~scanf("%d%d",&n,&m)&&(n!=0||m!=0))
{
sum =1;
m = m<(n-m)?m:n-m;
for(k =1;k <= m;k++)
sum =(sum*(n-m+k))/k;
printf("%lld\n",sum);
}
return0;}