Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python calculating Catalan Numbers

I have code which is calculating catalan numbers with method of Binominal Coefficients.

def BinominalCoefficient(n,k):
    res = 1;
    if (k > n - k):
        k = n - k
    for i in range(k):
        res *= (n - i)
        res /= (i + 1)
    return res
def CatalanNumbers(n):
   c = BinominalCoefficient(2*n, n)
   return (c//(n+1))
print (CatalanNumbers(510))

I have a "nan" result when i try to calculate Catalan number which n is more than 510. Why this is happening? And how can i solve it?

like image 665
Reodont Avatar asked Jul 16 '15 16:07

Reodont


People also ask

What is the best way to implement Catalan numbers in terms of time complexity?

Using Binomial Coefficient:Catalan numbers can also be represented as Catalan(n)=2nCn/(n+1). This reduces the time complexity to:O(n).

How do I prove Catalan numbers?

This can be proved by using the asymptotic growth of the central binomial coefficients, by Stirling's approximation for. , or via generating functions. The only Catalan numbers Cn that are odd are those for which n = 2k − 1; all others are even. The only prime Catalan numbers are C2 = 2 and C3 = 5.


2 Answers

I assume you're using Python 3.

Your res /= (i + 1) should be res //= (i + 1) to force integer arithmetic:

def BinominalCoefficient(n,k):
    res = 1
    if (k > n - k):
        k = n - k
    for i in range(k):
        res *= (n - i)
        res //= (i + 1)
    return res
def CatalanNumbers(n):
   c = BinominalCoefficient(2*n, n)
   return (c//(n+1))
print (CatalanNumbers(511))

returns

2190251491739477424254235019785597839694676372955883183976582551028726151813997871354391075304454574949251922785248583970189394756782256529178824038918189668852236486561863197470752363343641524451529091938039960955474280081989297135147411990495428867310575974835605457151854594468879961981363032236839645

You get nan because the divison /= in Python 3 returns a float which overflows to inf.

like image 96
xnx Avatar answered Oct 27 '22 00:10

xnx


In addition to xnx's answer, note that starting Python 3.8, with the addition of math.comb (binomial coefficient) in the standard library, we can also calculate Catalan numbers as such:

import math

def catalan(n):
  return math.comb(2*n, n) / (n+1)

catalan(511) # 2.1902514917394773e+303
like image 21
Xavier Guihot Avatar answered Oct 26 '22 22:10

Xavier Guihot