[英]Binomial coefficient programm outputs wrong results, if inputs are large(C++)
I have created a programm, that calculates binomial coefficient: 我创建了一个程序,用于计算二项式系数:
#include <iostream>
#include <string>
using namespace std;
int factorial(int num){
int res = 1;
for(int i = 1;i <= num; ++i){
res *= i;
}
return res;
}
int binom(int n,int k){
int factorial(int num);
int binom_coef;
binom_coef = factorial(n)/(factorial(k)*factorial(n-k));
return binom_coef;
}
int main(){
int n,k;
int binom(int n,int k);
try{
cout << "Enter number n:";
cin >> n;
cout << "Enter number k:";
cin >> k;
if(n < k){
throw -1;
}
cout << binom(n,k) << "\n";
}catch(int x)
cout << "n must be biggger than k";
}
For small inputs(up to 10) everything works perfectly fine. 对于较小的输入(最多10个),一切正常。 But if I enter big enough n and k(more than 10) the calculations are totally wrong and I cannot figure out why is that.
但是,如果我输入足够大的n和k(大于10),则计算是完全错误的,而且我不知道为什么会这样。
Can you help me? 你能帮助我吗?
The factorial is a function that grows really fast. 阶乘是一项功能,可以快速增长。 It may be that for
n > 10
your factorials already overflow the int
type. 可能是对于
n > 10
您的阶乘已经溢出了int
类型。
In fact, 12!
其实
12!
= 479001600
=
479001600
You're applying the theoretical formula for the binomial coefficient, but if you try the operative definition you may have less problems: 您正在应用二项式系数的理论公式,但是,如果尝试操作性定义,则可能会遇到较少的问题:
10 : 2 = 10! / (2! * 8!) = (10 * 9) / (2 * 1)
So what you can do is: multiply all numbers in [n, n - k)
, then divide them for all the numbers in [k, 1)
. 因此,您可以做的是:将
[n, n - k)
所有数字相乘,然后将它们除以[k, 1)
所有数字。
int bin_coeff(int n, int k) {
int res = 1, i = n;
while (i > n - k) res *= i--;
while (i > 0) res /= i--;
return res;
}
As you can see, you'll calculate 10 : 2
by simply doing 90 / 2
, which are not big numbers, and you'll even get a better efficiency for your algorithm. 如您所见,只需执行
90 / 2
即可算出10 : 2
,这不是一个很大的数字,您甚至可以获得算法的更高效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.