Why does my program returns an error when encountered with large value like n = 4100 and k = 3? Im assuming its because of integer overflow but the solution given (which uses int as well) works fine. How can I fix this issue?
Expected:
Enter n and k: 4100 3
4100 choose 3 = 11478429700
Actual result:
Floating point exception (core dumped)
My code:
#include <stdio.h>
#include <stdlib.h>
void exit_if(int condition, char *err);
int n_choose_k(int n, int k);
int factorial(int x);
int
main(int argc, char *argv[]) {
int n, k;
// read the values
printf("Enter n and k: ");
exit_if(scanf("%d %d", &n, &k) != 2, "scanf failed to read values\n");
// scaffolding for n_choose_k
printf("%d choose %d = %d\n", n, k, n_choose_k(n, k));
return EXIT_SUCCESS;
}
void
exit_if(int condition, char *err) {
if (condition) {
printf("%s", err);
exit(EXIT_FAILURE);
}
}
// to calculate the combination
int
n_choose_k(int n, int k) {
int numer, denom;
numer = factorial(n);
denom = factorial(n - k) * factorial (k);
return numer / denom;
}
// to calculate the factorial (helper fn for combination)
int
factorial(int x) {
exit_if(x < 0, "factorial of a negative integer is not defined\n");
int ans = 1;
for (int i = 2; i <= x; i++)
ans *= i;
return ans;
}