pythoncatalan

Catalan number calculation using Python?


I am writing a Python code to generate Catalan numbers using the mathematical formula given here:

C(0) = 1 and C(n) = (2(2n − 1) / (n + 1)) * C(n − 1) per this website here. (https://rosettacode.org/wiki/Catalan_numbers)

However, when I am writing it in python as a function, it gives me false results.

eg: For 20 answer should be 6564120420.0 while my code gives me 344373768.

Here:

def catalan(cat_input):

    if cat_input==0:
    return 1 

    else:
    return  (((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1))

Can someone help me figure this out please ?


Solution

  • The problem is when dividing /. As-is the result (of the division itself, before multiplying) may not be whole number, and since / in python2 is by default int-division the decimal part gets "cropped" and you get the wrong results.

    There are couple ways to fix that (pick your favorite):

    Edit: In general (at least in python) it is advised not to use recursion if possible, as it is not efficient and you may run to problems like recursion limit