Using unsigned long or unsigned long long gives 4075. So there must be wrapping into negative numbers.
Indeed, the first at:
n=34 r=16 C[n][r]=-2091005866
with 32 bit and 64 bit. So you will have to use something larger than 64 bits, and be able to detect wrapping by using signed numbers.
Add test: if (C[n][r] < 0)
in the loop to detect.
As you only need precision close to 1,000,000, switch to one of the floating point numbers is the answer. double does it. With floating point numbers, underflow is the issue eg: 999,999 + 1 => 999,999.
Because at some point the number you want to store is too big to fit inside long int (this is an overflow).
I'll try to explain by using char instead of long.
char is mostly used to encode characters, however it is actually a very small integer (on most computers it is an octet -- it has a length of 8 bits, whereas long has 32 or 64 bits).
in memory, a char looks like:
bbbbbbbb (8 bits, each is either 1 or 0)
10011101 (for example)
If the char is signed, the first bit is the sign.
If the char is unsigned, the first bit is part of the value.
What this means is that signed char can have values from -128 to 127.
While unsigned char can have values from 0 to 255.
Another way to check if nCr > 1000000 is:
nCr = n! / [ (n-r)! * r! ]
nCr = [n*(n-1)*(n-2)*...*(n-r+1)] / [1*2*3*...*r]
Can be calculated recursive as:
k1 = n / 1
k2 = k1 * (n-1) / 2
k3 = k2 * (n-2) / 3
k4 = k3 * (n-3) / 4
...
kr = k(r-1) * (n-r+1) / r
with k(i) >= k(i-1). So you just have to calculate the multiplication up to k(i) where k(i) > 1 mil., not the whole kr = nCr which causes overflow. This stament is true when r <= n/2...
.
n*(n-1) will divided by 2, because 2 consecutive natural numbers will have 1 number divided by 2, and n*(n-1)*(n-2) will have 1 number divided by 3, etc... So don't worry about integer division in k1, k2, k3, k4, ..., kr.
There is no need to use integers as you only need to determine when the answer is >1,000,000. Using 64 bit doubles (binary64) works as 100! (9.332621544×10¹⁵⁷) < numeric_limits<double>::max() (1.79769e+308) so there will be no overflow when using 64 bit doubles. The critical issue is that there is precision of at least 1 when doing many summations of numbers less than 1,000,000 so nothing is lost with each addition. 64 bit doubles have approximately 15-16 decimal digits of precision.
Ref:http://en.wikipedia.org/wiki/IEEE_floating_point