integer - Binomial coefficient function C++ incorrect answer n>13 -


i'm trying learn c++ , hence i'm trying function calculate binomial coefficient. code works n of 12, larger values generated result incorrect. i'm grateful input.

long double binomial(int n, int k) { int d = n-k; int = 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 integer n: \n"; cin >> n; cout << "select integer k: \n"; cin >> k;  long double v = binomial(n,k); cout << "the binomial coefficient is: " << v << "\n"; return 0; } 

if int 32 bits long on system (very common nowadays), factorial of 13 doesn't fit (6227020800 > 2147483647).

either transition bigger (unsigned long long, anyone?), or use bigint library, or come better/more clever algorithm doesn't involve computing large factorials, @ least not directly.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -