MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / NthCatalanNumber

Function NthCatalanNumber

dynamic/catalan.go:15–33  ·  view source on GitHub ↗

NthCatalan returns the n-th Catalan Number Complexity: O(n²)

(n int)

Source from the content-addressed store, hash-verified

13// NthCatalan returns the n-th Catalan Number
14// Complexity: O(n²)
15func NthCatalanNumber(n int) (int64, error) {
16 if n < 0 {
17 //doesn't accept negative number
18 return 0, errCatalan
19 }
20
21 var catalanNumberList []int64
22 catalanNumberList = append(catalanNumberList, 1) //first value is 1
23
24 for i := 1; i <= n; i++ {
25 catalanNumberList = append(catalanNumberList, 0) //append 0 and calculate
26
27 for j := 0; j < i; j++ {
28 catalanNumberList[i] += catalanNumberList[j] * catalanNumberList[i-j-1]
29 }
30 }
31
32 return catalanNumberList[n], nil
33}

Callers 1

TestCatalanNumbersFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestCatalanNumbersFunction · 0.68