I'm still quite new to C++, but I tried to generate a function to calculate 40 choose 20. The main problem I come across though is that double does not given enough decimal point precision to accurately calculate this, here is my code;
#include <iostream>
using namespace std;
int main(){
double n = 1;
for(double i=20;i>1;i--){
n = n*((20+i)/i);
cout << n << " " << i << endl;
}
cout << n << endl;
}
The couts are purely to see what's being calculated. If you run this yourself you see that for the i=9 the result is 44350.7, the problem being that it always seems to take it to 6 significant figures which causes issues in the calculation. Is it possible to address this issue?
Or should I just use some pre-defined binomial coefficient function (where would I find one?).
EDIT: I'm sorry, but this got linked to a previous answer but that has been less than useful. Even copying the code from the linked thread produces the correct answer for 600 choose 3, but the wrong answer for 40 choose 20 (comparing answers with wolfram answer for instance shows this). It is also not very new-user friendly and it doesn't seem to make sense why "result" would be classed as int when we're dividing, and obtaining results that are NOT integers. Indeed it works for 600 choose 3 because we only ever divide by 3 and 2, which happens to work out conveniently for that case.
This is why I stuck with doubles because the loop requires, at some points, numbers that are not full integers. Doubles would be fine, surely, if it wasn't for the fact the precision is not high enough to produce correct answers.