pythoncatalan

Basic Catalan numbers


I wanna write a program that prints out all Catalan numbers less than or equal to say 100000.

Such are given by cn=1 and cn1 = ((4n+2)/n+2)*cn (next value). When I try it I get the below error.

My code is :

 cn,cn1 = 1,2
 n = 1 
 while cn1<100000:
       cn1 = ((4(n+2)/(n+2)))*cn
       print(cn1)

My output error:

runfile('C:/Users/Admin/Desktop/cpy/ex_cat_numbe.py', wdir='C:/Users/Admin/Desktop/cpy') Traceback (most recent call last):

File "", line 1, in runfile('C:/Users/Admin/Desktop/cpy/ex_cat_numbe.py', wdir='C:/Users/Admin/Desktop/cpy')

File "C:\Users\Admin\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace)

File "C:\Users\Admin\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Admin/Desktop/cpy/ex_cat_numbe.py", line 11, in cn1 = ((4(n+2)/(n+2)))*cn

TypeError: 'int' object is not callable


Solution

  • You're not using the correct formula to calculate Catalan number. Here is the code to print Catalan numbers less than or equal to 100000:

    # A recursive function to find nth catalan number
    def catalan(n):
        # Base Case
        if n <= 1:
            return 1
    
        # Catalan(n) is the sum of catalan(i)*catalan(n-i-1)
        res = 0
        for i in range(n):
            res += catalan(i) * catalan(n - i - 1)
    
        return res
    
    
    n = 0
    c = catalan(n)
    while c <= 100000:
        print(c)
        n += 1
        c = catalan(n)
    

    Output:

    1
    1
    2
    5
    14
    42
    132
    429
    1430
    4862
    16796
    58786
    

    For more information about the code check this link.