I'm always reluctant to use floats to compute this kind of integers... Between the chances of rounding errors and the missing digits, it's not great. At n=176, you've far below the normalized doubles when you compute 1/(n!), I'd be curious to know whether your last values are actually good.
If you want to check, Cat(176) is exactly, if I'm not mistaken 2202649981138949529709608229856778034894847921317741692970659784491657853623950138141866464005163908232
And Cat(175) = 555369012338453086550713186160469675464940287853618631988328749081229971640226744232350946052584062332
That's a pity that C lacks native arbitrary long integers... Even my calculator is doing it ^_^
Is this some assignement about dynamic programming? Do you have to compute a single one or many/all of them?
If you have a single catalan number to compute, I'd say the method is correct (minus the float issue I talked above)... Cat
is nCr(2n, n)/(n/1) and you actually used the nCr(n, k) = n*nCr(n-1, k-1)/k relation which is usually a pretty efficient way to compute the combination.
But, like you saw, you're limited to n=176 because of the way real numbers work.
If you have to compute all of them, or want to go further, you can see that your formula gives Cat
= Cat(n-1)*(4*n-2)/(n+1) with Cat(1)=1, which should be an efficient manner to generate all of them. You can keep all computed values in a table, and when you have to compute one, if it's not already in the table, fill the table starting at the biggest computed yet and iterate using the recursion formula.
You can reach Cat(519) this way (by doing the division BEFORE the multiplication), with the first 14 digits corrects if I'm not mistaken.
The exact value for Cat(519)
140239043650914933309771256012337161301472611398544757325664370049865751420453458821350670408676263462548127750393958019426775488055871200139933800366329620082724993869266473333310721268298552396471937748379893211937643818403427162436366946974972682374621242035332097535261433136817732374480806452523112121550
After that, the numbers are too big for IEEE doubles, so you can't possibly go further with doubles.
A better solution to compute the number would be to use an Eratosthene sieve to compute the exponents of the prime decomposition of each integers between 1 and 2n, and when you do your test, adding or substracting those exponents ot as many counters as you have primes. That'll give you the list of exponents for the prime decomposition of Cat
. It's an exact solution, and will work for as large a n as you want, although computing the actual value will be a bit trickier in C if you want values larger than the larger double (but doable).