binomial-coefficients

Fast n choose k mod p for large n?

删除回忆录丶 提交于 2019-11-26 21:41:04
What I mean by "large n" is something in the millions. p is prime. I've tried http://apps.topcoder.com/wiki/display/tc/SRM+467 But the function seems to be incorrect (I tested it with 144 choose 6 mod 5 and it gives me 0 when it should give me 2) I've tried http://online-judge.uva.es/board/viewtopic.php?f=22&t=42690 But I don't understand it fully I've also made a memoized recursive function that uses the logic (combinations(n-1, k-1, p)%p + combinations(n-1, k, p)%p) but it gives me stack overflow problems because n is large I've tried Lucas Theorem but it appears to be either slow or

Which is better way to calculate nCr

泄露秘密 提交于 2019-11-26 12:07:34
问题 Approach 1: C(n,r) = n!/(n-r)!r! Approach 2: In the book Combinatorial Algorithms by wilf, i have found this: C(n,r) can be written as C(n-1,r) + C(n-1,r-1) . e.g. C(7,4) = C(6,4) + C(6,3) = C(5,4) + C(5,3) + C(5,3) + C(5,2) . . . . . . . . After solving = C(4,4) + C(4,1) + 3*C(3,3) + 3*C(3,1) + 6*C(2,1) + 6*C(2,2) As you can see, the final solution doesn\'t need any multiplication. In every form C(n,r), either n==r or r==1. Here is the sample code i have implemented: int foo(int n,int r) {

Number of combinations (N choose R) in C++

你。 提交于 2019-11-26 09:09:21
问题 Here I try to write a program in C++ to find NCR. But I\'ve got a problem in the result. It is not correct. Can you help me find what the mistake is in the program? #include <iostream> using namespace std; int fact(int n){ if(n==0) return 1; if (n>0) return n*fact(n-1); }; int NCR(int n,int r){ if(n==r) return 1; if (r==0&&n!=0) return 1; else return (n*fact(n-1))/fact(n-1)*fact(n-r); }; int main(){ int n; //cout<<\"Enter A Digit for n\"; cin>>n; int r; //cout<<\"Enter A Digit for r\"; cin>>r