Catalan Number Series in Java

In combinatorial mathematics, the Catalan numbers are a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects. They are named after the French-Belgian mathematician Eugène Charles Catalan.

The nth Catalan number can be expressed as:

The first Catalan numbers for n = 0, 1, 2, 3, … are:
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, …

Write a Java program to display the first N terms of the Catalan series.

import java.util.Scanner;
class Catalan{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("N = ");
        int n = in.nextInt();
        if(n <= 0){
            System.out.println("The number N must be at least 1.");
            return;
        }
        for(int i = 1; i <= n; i++){
            int j = i - 1;
            long result = fact(2 * (j)) / (fact(j + 1) * fact(j));
            System.out.print(result + " ");
        }
    }
    public static long fact(int n){
        long f = 1L;
        for(int i = 1; i <= n; i++)
            f *= i;
        return f;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *