Search code examples
c++integeroverflowbinomial-coefficients

Binomial coefficient function C++ incorrect answer n>13


I'm trying to learn C++ and hence I'm trying to do a function to calculate the binomial coefficient. The code works up to a n of 12, for larger values the generated result is incorrect. I'm grateful for your input.

long double binomial(int n, int k) {
int d = n-k;
int i = 1, t = 1, n1 = 1, n2 = 1;
if (d == 0) {
    return 1;
} else if (n==0) {
    return 1;
} else {
    while (i <=n) {
        t *= i;
        if (i == d) {
            n1 = t;
            cout << t;
        }
        if (i == k) {
            n2 = t;
            cout << t;
        }
        i++;
    }
}
return t/n1/n2;
}
int main() {
int n, k;
cout << "Select an integer n: \n";
cin >> n;
cout << "Select an integer k: \n";
cin >> k;

long double v = binomial(n,k);
cout << "The binomial coefficient is: " << v << "\n";
return 0;
}

Solution

  • If int is 32 bits long on your system (very common nowadays), then the factorial of 13 doesn't fit into it (6227020800 > 2147483647).

    Either transition to something bigger (unsigned long long, anyone?), or use a bigint library, or come up with a better/more clever algorithm that doesn't involve computing large factorials, at least not directly.