I am attempting to do some statistics-related functions so I can carry out a few related procedures (ie: statistics calculations for probabilities, generate Pascal’s triangle for an arbitrary depth, etc).
I have encountered an issue where I am likely dealing with overflow. For example, if I want to calculate nPr for (n=30,p=1), I know that I can reduce it to:
30P1 = 30! / (30 - 1)!
= 30! / (29)!
= 30! / 29!
= 30
However, when calculating using the functions below, it looks like I will always get invalid values due to integer overflow. Are there any workarounds that don’t require the use of a library to support arbitrarily large numbers? I’ve read up a bit in other posts on the gamma functions, but couldn’t find concrete examples.
int factorial(int n) {
return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
int nCr(int n, int r) {
return (nPr(n,r) / factorial(r));
//return factorial(n) / factorial(r) / factorial(n-r));
}
int nPr(int n, int r) {
return (factorial(n) / factorial(n-r));
}
You look like you are on the right track, so here you go:
To compile, do:
gcc -lm myFile.c && ./a.outNote that the accuracy of your results is limited by the bit-depth of the
doubledata type. You should be able to get good results with this, but be warned: replacing all theints above withlong long unsignedmay not necessarily guarantee accurate results for larger values ofn,r. At some point, you will still need some math library to handle arbitrarily large values, but this should help you avoid that for smaller input values.