ncr in c (combinations)

怎甘沉沦 提交于 2019-12-13 03:06:50

问题


I m trying to calculate ncr(combinations) in c using dp. But it is failing with n=70. Can anyone help?

unsigned long long ncr( int n , int r)
{
unsigned long long c[1001];
int i=1; 
c[0]=1;
for(i=1; i<=r; i++)
    c[i]= ((unsigned long long) (c[i-1]) * (unsigned long long)( n-i+1))%(unsigned long long) (1000000007)/ (unsigned long long)(i);
return c[r];
}

basic idea is ncr = ((n-r+1)/r)* nc(r-1)


回答1:


The intermediate product (unsigned long long) (c[i-1]) * (unsigned long long)( n-i+1) is a very big number, and is overflowing the 64 bits word.

You may want to use bignums. I strongly recommend against developing your own bignum functions (e.g. multiplication and division of bignums), because it is a delicate algorithmic subject (you could still get a PhD about that).

I suggest using some existing bignum library like GMP.

Some languages or implementations (in particular SBCL for Common Lisp) offers native bignum operations. But standard C or C++ don't.




回答2:


Make the division before the multiplication. a*b/c = (a/c) *b where the second better for overflow which seems your problem.



来源:https://stackoverflow.com/questions/14787838/ncr-in-c-combinations

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