Catalan numbers

You are encouraged to solve this task according to the task description, using any language you may know.


Catalan numbers are a sequence of numbers which can be defined directly:






C

n


=


1

n
+
1






(



2
n

n


)



=



(
2
n
)
!


(
n
+
1
)
!

n
!





 for 

n
≥
0.


{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}


Or recursively:






C

0


=
1


and



C

n
+
1


=

∑

i
=
0


n



C

i




C

n
−
i




for 

n
≥
0
;


{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}


Or alternatively (also recursive):






C

0


=
1


and



C

n


=



2
(
2
n
−
1
)


n
+
1




C

n
−
1


,


{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}




Task

Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.

Memoization   is not required, but may be worth the effort when using the second method above.



Related tasks

Catalan numbers/Pascal's triangle
Evaluate binomial coefficients


print "non-recursive version"
print catNonRec(5)
for i = 0 to 15
    print i;"   =   "; catNonRec(i)
next
print
 
print "recursive version"
print catRec(5)
for i = 0 to 15
    print i;"   =   "; catRec(i)
next
print
 
print "recursive with memoisation"
redim cats(20)  'clear the array
print catRecMemo(5)
for i = 0 to 15
    print i;"   =   "; catRecMemo(i)
next
print
 
 
wait
 
function catNonRec(n)   'non-recursive version
    catNonRec=1
    for i=1 to n
        catNonRec=((2*((2*i)-1))/(i+1))*catNonRec
    next
end function
 
function catRec(n)  'recursive version
    if n=0 then
        catRec=1
    else
        catRec=((2*((2*n)-1))/(n+1))*catRec(n-1)
    end if
end function
 
function catRecMemo(n)  'recursive version with memoisation
    if n=0 then
        catRecMemo=1
    else
        if cats(n-1)=0 then    'call it recursively only if not already calculated
            prev = catRecMemo(n-1)
        else
            prev = cats(n-1)
        end if
        catRecMemo=((2*((2*n)-1))/(n+1))*prev
    end if
    cats(n) = catRecMemo    'memoisation for future use
end function