c语言实现求组合数(带点优化的思想,防止溢出)

来源:互联网 发布:淘宝暴露狂买家秀 编辑:程序博客网 时间:2024/05/21 10:34


这是大家都知道的组合数,思想也很简单,但是里面的阶乘,容易溢出,让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);}




1 0
原创粉丝点击