Skip to content

Instantly share code, notes, and snippets.

@OzTamir
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save OzTamir/480d89a83b8ce03c5601 to your computer and use it in GitHub Desktop.

Select an option

Save OzTamir/480d89a83b8ce03c5601 to your computer and use it in GitHub Desktop.
Calculate the n-th Catalan number
from __future__ import division
import sys
def calc_mod(n, m):
''' Calculate the n-th Catalan mod m'''
res = 1
tmp = 0
for k in xrange(2, n + 1):
tmp = ((n + k) / k) % m
res %= m
res *= tmp
return res
# Optimize factorial using memoization
memo_dict = {}
def factorial(n):
''' Calculate the factorial of n '''
if n <= 1:
return 1
if n in memo_dict:
return memo_dict[n]
memo_dict[n] = factorial(n - 1) * n
return memo_dict[n]
def calc(n):
''' Calculate the n-th Catalan number '''
numerator = factorial(2 * n)
denominator = (factorial(n + 1)) * (factorial(n))
return numerator / denominator
def main(args):
if int(args[0]) % 2 != 0:
print 'Error: please enter an even number'
return
if len(args) == 2:
ans = calc_mod(int(args[0]) // 2, int(args[1]))
else:
ans = calc(int(args[0]) // 2)
print 'The Answer is: %d' % ans
return
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'Usage: python calc_catalan.py num [mod]'
sys.exit(1)
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment