Factorials are usually very large, so you just have integer overflows. To fix this problem, you can implement any other algorithm for computing C(n, k)
without using factorials, for example:
unsigned long long C(unsigned n, unsigned k) { if (n == k || k == 0) { return 1;
The following repeating rule is used here: C(n, k) = C(n - 1, k - 1) * n / k
. This is very easy to prove, since C(n, k) = n! / (k! (nk)!) = (n/k) * (n-1)! / ((k-1)!(n-1-k+1)!)
C(n, k) = n! / (k! (nk)!) = (n/k) * (n-1)! / ((k-1)!(n-1-k+1)!)
C(n, k) = n! / (k! (nk)!) = (n/k) * (n-1)! / ((k-1)!(n-1-k+1)!)
.
source share