How to resolve the algorithm Catalan numbers step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Catalan numbers step by step in the Nim programming language
Table of Contents
Problem Statement
Catalan numbers are a sequence of numbers which can be defined directly: Or recursively: Or alternatively (also recursive):
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.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Catalan numbers step by step in the Nim programming language
Source code in the nim programming language
import math
import strformat
proc catalan1(n: int): int =
binom(2 * n, n) div (n + 1)
proc catalan2(n: int): int =
if n == 0:
return 1
for i in 0..<n:
result += catalan2(i) * catalan2(n - 1 - i)
proc catalan3(n: int): int =
if n > 0: 2 * (2 * n - 1) * catalan3(n - 1) div (1 + n)
else: 1
for i in 0..15:
echo &"{i:7} {catalan1(i):7} {catalan2(i):7} {catalan3(i):7}"
You may also check:How to resolve the algorithm Long primes step by step in the Maple programming language
You may also check:How to resolve the algorithm Pick random element step by step in the PHP programming language
You may also check:How to resolve the algorithm Date manipulation step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Magic constant step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Partition an integer x into n primes step by step in the Kotlin programming language