×

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects.

Mathematical formula of Catalan number

Coming to the technical aspects of Catalan numbers, we are often asked to find whether a given number is a Catalan number or not. So how do we do that?

For that, we have steps to identify it.

Firstly, in the mathematical formula, assign a positive integer value to the variable n.

Then find the 2nCn ,n value will be any integer taken in step 1.

i.e 2nCn =  (2n!)/((n+1)!n!)

Uses of Catalan number

  • Catalan number is applied in finding the no of binary search trees possible with the n keys.
  • Also used to find the permutations of 1...n by avoiding a pattern such as 123 or 1234
  • And into how many triangles a polygon of n+2 sides can be split by connecting the vertices.
  • The number of full btrees.
  • First few catalan numbers can be 1,1,2,5,14,42,132,429, 1430....where n can be 0,1,2,3.....

CatlnNumber.java:

class CatlnNumber {
    // this logic serves the procedure for a recursive function to find the nth Catln number
    int Catln (int n)
    {
        int result = 0;
        // Base condition 
        if (n <= 1)
        {
            return 1;
        }
        for (int i = 0; i < n; i++)
        {
            result += Catln(i) * Catln(n - i - 1);
        }
        return result;
    }
    public static void main (String [] args)
    {
        CatlnNumber cn = new CatlnNumber ();
        for (int i = 0; i < 10; i++)
        {
            System.out.print (cn.Catln (i) + " ");
        }
    }
}

Output:

Catalan number in Java

CatlnNumber1.java:

import java.io.*;
import java.util.*;


class CatlnNumber {
 
    // A dynamic programming method or function that can be used to find nth
    // catln number
    static int CatlnDP(int n)
    {
        // store results of subproblems
        int catln[] = new int[n + 2];
 
        // Initialization first two catalan values into the table
        catln[0] = 1;
        catln[1] = 1;
 
        // Filling the entries into catln[]
        // using the recursive formula
        for (int i = 2; i <= n; i++) {
            catln[i] = 0;
            for (int j = 0; j < i; j++) 
           {
                catln[i] += catln[j] * catln[i - j - 1];
            }
        }
 
        // Returning the last entry
        return catln [n];
    }
    public static void main (String [] args)
    {
        Scanner scan = new Scanner (System.in);
        System.out.println("enter the cat");
        int cat=scan.nextInt();
        for (int i = 0; i < cat; i++) 
       {
            System.out.println(CatlnDP(i) + " ");
        }
    }
}

Output:

Catalan number in Java

Using binomial coefficient:

CatlnNumber.java

import java.io.*;
import java.util.*;
class CatlnNumber {
 
    // Returns value of Binomial Coefficient C(n, k)
    static long binoCoeff(int n, int k)
    {
        long result= 1;
 
        // Since C(n, k) = C(n, n-k)
        if (k > n - k) {
            k = n - k;
        }
 
        // Calculating the value of [n*(n-1)*---*(n-k+1)] /
        // [k*(k-1)*---*1]
        for (int i = 0; i < k; ++i) {
            result *= (n - i);
            result /= (i + 1);
        }
 
        return result;
    }
 
    // using the binomial coefficient concept to generate a function 
    //  that finds nth catln number in O(n) time
    static long Catalan (int n)
    {
        // Calculate value of 2nCn
        long c = binoCoeff(2 * n, n);
 
        // return 2nCn/(n+1)
        return c / (n + 1);
    }


    public static void main (String [] args)
    {
        Scanner scan = new Scanner (System.in);
        System.out.println ("enter the cat");
        int cat=scan.nextInt ();


        for (int i = 0; i < cat; i++) {
            System.out.println (catalan(i) + " ");
        }
    }
}

Output:

Catalan number in Java

We can calculate up to 80 Catalan numbers by using the above method. For numbers greater than 80, we prefer using the BigInteger method in Java.

By using Big Integer:

CatlnNumber.java

import java.io.*;
import java.util.*;
import java. math.*;


class CatlnNumber
{
        public static BigInteger CatalnFind(int n)
       {
             // using BigInteger to find out the factorials of larger numbers
              BigInteger big = new BigInteger("1");
                  // calculating factorial of n
             for (int i = 1; i <= n; i++) 
            {
                  big = big.multiply(BigInteger.valueOf(i));
             }
            // n! * n!
            big = big.multiply(big);


           BigInteger de = new BigInteger("1");
           // calculate (2n)!
          for (int i = 1; i <= 2 * n; i++) 
         {
                de = de.multiply(BigInteger.valueOf(i));
}


                // calculate (2n)! / (n! * n!)
               BigInteger answer = de.divide(big);
              // calculate (2n)! / ((n! * n!) * (n+1))
              answer = answer.divide(BigInteger.valueOf(n + 1));
              return answer;
             }
              public static void main (String [] args)
               {
                         Scanner scan = new Scanner (System.in);
                         System.out.println ("enter the nth cat");
                         int cat = scan.nextInt();
                         System.out.println (CatalnFind (cat));    
                  }
}

Output:

Catalan number in Java

Related Topics

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.