我想用C做一个数学组合计算器。例如,5组合2是10。即使使用unsigned long long
类型,我的程序中也会出现溢出问题。输入源是 n 和 m。每个数字都是 (5<= n,m <= 100) 和 (m<=n) 绑定的。另外,我在下面附上了我的代码。有没有我不知道的更大数字类型或解决方案?请告诉我。提前感谢您的帮助。
#include <stdio.h>
static unsigned long long gcd(unsigned long long a, unsigned long long b)
{
if(a<b)
return gcd(b, a);
if(b==0)
return a;
return gcd(b, a%b);
}
int main()
{
unsigned long long n, m1, m2, i, j, temp, denominator[101] = {1,}, numerator[101] = {1,}, total_de = 1, total_nu = 1, gcd_result;
scanf("%llu %llu",&n, &m1);
m2 = n - m1;
if(m2 < m1)
{
temp = m1;
m1 = m2;
m2 = m1;
}// m1 is small
denominator[0] = 1; numerator[0] = 1;
for(i=1; i<=m1; i++)
{
denominator[i] = n--;
numerator[i] = i;
}
for(i = 1; i<=m1; i++)
{
for(j = 1; j<=m1; j++)
{
gcd_result = gcd(denominator[i], numerator[j]);
denominator[i] /= gcd_result;
numerator[j] /= gcd_result;
}
}
for(i = 1; i<=m1; i++)
{
total_de *= denominator[i];
total_nu *= numerator[i];
}
// sometimes overflow happened
printf("%llu\n",total_de/total_nu);
return 0;
}