欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

c 实现查找组合数(包括一些防止溢出的优化想法)

最编程 2024-04-08 19:25:58
...


这是大家都知道的组合数,思想也很简单,但是里面的阶乘,容易溢出,让m!/n!先约分,减小数的大小,m!/n! = (n+1)(n+2)(n+3)···(m-1)(m);

如果m-n > n的话,我们就让n = m-n.j尽可能让乘起来的数小一点。代码打印的是25里面选12个的组合数 5200300.

#include <stdio.h>

long long factorial(int m, int n)
{
	long long ans = 1;
	if(m < n-m) m = n-m;
	for(int i = m+1; i <= n; i++) ans *= i;
	for(int j = 1; j <= n - m; j++) ans /= j;
	return ans;
	  
}

int main()
{
	int m, n;
	long long count = 0;
	scanf("%d %d", &m, &n);
	count = factorial(m, n);
	printf("%I64d", count);
}




推荐阅读