0

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 ?

R_Moose
  • 103
  • 9

1 Answers1

0

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):

  • Change the order in the equation, instead of (((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1)) use (((4*cat_input) - 2) * (catalan(cat_input-1)) / (cat_input + 1)), that way you are guaranteed to get whole number after division
  • change the type of the first part of the equation to float to force float division: (float((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1))
  • Use python3 instead of python2 as python3 uses decimal division by default
  • Use from __future__ import division to "activate" python3-like division

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

Drecker
  • 1,215
  • 10
  • 24