binomial coefficient

一曲冷凌霜 提交于 2019-12-13 04:17:40

问题


I have a code which calculate binomial coefficient, but when number is bigger then 20, it start to calculate wrong, where is the problem? Thanks

#include <iostream>
using namespace std;

long int bin(long int x)
{
    if(x==0)
        return 1;
    long int r = x;
    for(int i = r-1;i>0;i--)
    {
        r = r*i;
    }
    return r;
}
int main()
{
    cout << "Write n and k: " << endl;
    long int n=0;
    long int k=0;
    cin >> n;
    cin >> k;
    long int result = 0;
    long int fn = bin(n);
    long int fk = bin(k);
    long int fnk = bin(n-k);


    result = fn/(fk*fnk);

    cout << endl << "C = " << result << endl;


    return 0;
}

for example 12 and 5 = 792 which is correct, but 20 and 4 = -2 which is not correct


回答1:


Your bin function computes the factorial. The factorial of 21 doesn't fit in a long.

You're already relying on an implementation detail. long is only required to be 32 bits, but on your system it's 64. If it were only 32, then you'd fail much sooner.




回答2:


20! = 2432902008176640000, which is far beyond what long int can hold (typically 2147483647). Use double instead.




回答3:


You are calculating the factorial of n using

bin(n);

You are running past the limit of long when n is >=20.

As @SteveJessop pointed out in the comments, You would overrun the limit even if you used unsigned long long (the longest fixed-point type) which has a range from 0 to 18446744073709551615

You could use an int-array to store your result as detailed here.



来源:https://stackoverflow.com/questions/13156584/binomial-coefficient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!