I am calculating combination(15, 7) in C++.
I first used the following code and get the wrong answer due to a type promotion error.
#include <iostream> int main() { int a = 15; double ans = 1; for(int i = 1; i <= 7; i++) ans *= (a + 1 - i) / i; std::cout << (int) ans; return 0; }
Output:
2520
So I changed
ans *= (a + 1 - i) / i;
toans *= (double)(a + 1 - i) / i;
and still get the wrong answer.#include <iostream> int main() { int a = 15; double ans = 1; for(int i = 1; i <= 7; i++) ans *= (double) (a + 1 - i) / i; std::cout << (int) ans; return 0; }
Output:
6434
Finally, I tried
ans = ans * (a + 1 - i) / i
, which gives the right answer.#include <iostream> int main() { int a = 15; double ans = 1; for(int i = 1; i <= 7; i++) ans = ans * (a + 1 - i) / i; std::cout << (int) ans; return 0; }
Output:
6435
Could someone tell me why the second one did not work?