There are 2 problems in your code:
fak_n
is not initialized in the fak()
function. You should write:
int fak(int n) {
int fak_n = 1;
for (int i = 2; i <= n; i++) {
fak_n = fak_n * i;
}
return fak_n;
}
type int
has a limited range, typically 31 bits, so it can only represent factorials up to fak(12)
, so computing bin(13,1)
which is 13
, will cause an arithmetic overflow and produce an incorrect value. You should use a larger type such as unsigned long long
and use a different formula.
Here is a modified version:
#include <stdio.h>
unsigned long long fak(int n) {
unsigned long long fak_n = 1;
for (int i = 2; i <= n; i++) {
fak_n = fak_n * i;
}
return fak_n;
}
unsigned long long bin(int n, int k) {
// check definition domain
if (k < 0 || k > n || n < 0)
return 0;
// use factorials for small values
if (n <= 20)
return fak(n) / fak(k) / fak(n - k);
// use Pascal triangle for larger ones
return bin(n - 1, k - 1) + bin(n - 1, k);
}
int main() {
int n, k;
if (scanf("%d%d", &n, &k) == 2) {
printf("%lld\n", bin(n, k));
}
return 0;
}