×

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

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.