How to resolve the algorithm Catalan numbers step by step in the Fantom programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Catalan numbers step by step in the Fantom 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 Fantom programming language

Source code in the fantom programming language

class Main
{
  static Int factorial (Int n)
  {
    Int res := 1
    if (n>1)
      (2..n).each |i| { res *= i }
    return res
  }

  static Int catalanA (Int n)
  { 
    return factorial(2*n)/(factorial(n+1) * factorial(n))
  }

  static Int catalanB (Int n)
  {
    if (n == 0)
    {
      return 1
    }
    else
    {
      sum := 0
      n.times |i| { sum += catalanB(i) * catalanB(n-1-i) } 
      return sum
    }
  }

  static Int catalanC (Int n)
  {
    if (n == 0)
    {
      return 1
    }
    else
    {
      return catalanC(n-1)*2*(2*n-1)/(n+1)
    }
  }

  public static Void main ()
  {
    (1..15).each |n|
    {
      echo (n.toStr.padl(4) + 
            catalanA(n).toStr.padl(10) +
            catalanB(n).toStr.padl(10) +
            catalanC(n).toStr.padl(10))
    }
  }
}

  

You may also check:How to resolve the algorithm Tonelli-Shanks algorithm step by step in the D programming language
You may also check:How to resolve the algorithm A+B step by step in the Nit programming language
You may also check:How to resolve the algorithm Möbius function step by step in the Factor programming language
You may also check:How to resolve the algorithm String interpolation (included) step by step in the LiveCode programming language
You may also check:How to resolve the algorithm A+B step by step in the XBS programming language