The Wayback Machine - https://web.archive.org/web/20241125024720/https://www.geeksforgeeks.org/program-nth-catalan-number/
Open In App

Program for nth Catalan Number

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Catalan numbers are defined as a mathematical sequence that consists of positive integers, which can be used to find the number of possibilities of various combinations. 

The nth term in the sequence denoted Cn, is found in the following formula: [Tex]\frac{(2n)!}{((n + 1)! n!)}               [/Tex] 

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

Catalan numbers occur in many interesting counting problems like the following.

  1. Count the number of expressions containing n pairs of parentheses that are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).
  2. Count the number of possible Binary Search Trees with n keys (See this)
  3. Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves.
  4. Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect.

See this for more applications. 

Examples:

Input: n = 6
Output: 132

Input: n = 8
Output: 1430

Program for nth Catalan Number using Recursion:

Catalan numbers satisfy the following recursive formula: [Tex]C_0=C_1=1 \ and \ C_{n}=\sum_{i=0}^{n-1}C_iC_{n-i-1} \ for \ n\geq 2            [/Tex]

Step-by-step approach:

  • Base condition for the recursive approach, when n <= 1, return 1
  • Iterate from i = 0 to i < n
    • Make a recursive call catalan(i) and catalan(n – i – 1) and keep adding the product of both into res.
  • Return the res.

Following is the implementation of the above recursive formula.  

C++
#include <iostream>
using namespace std;

// A recursive function to find nth catalan number
unsigned long int catalan(unsigned int n)
{
    // Base case
    if (n <= 1)
        return 1;

    // catalan(n) is sum of
    // catalan(i)*catalan(n-i-1)
    unsigned long int res = 0;
    for (int i = 0; i < n; i++)
        res += catalan(i) * catalan(n - i - 1);

    return res;
}

// Driver code
int main()
{
    for (int i = 0; i < 10; i++)
        cout << catalan(i) << " ";
    return 0;
}
Java
import java.io.*;

class CatalnNumber {

    // A recursive function to find nth catalan number

    int catalan(int n)
    {
        int res = 0;

        // Base case
        if (n <= 1) {
            return 1;
        }
        for (int i = 0; i < n; i++) {
            res += catalan(i) * catalan(n - i - 1);
        }
        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {
        CatalnNumber cn = new CatalnNumber();
        for (int i = 0; i < 10; i++) {
            System.out.print(cn.catalan(i) + " ");
        }
    }
}
Python
# A recursive function to
# find nth catalan number


def catalan(n):
    # Base Case
    if n <= 1:
        return 1

    # Catalan(n) is the sum
    # of catalan(i)*catalan(n-i-1)
    res = 0
    for i in range(n):
        res += catalan(i) * catalan(n-i-1)

    return res


# Driver Code
for i in range(10):
    print(catalan(i), end=" ")
# This code is contributed by
# Nikhil Kumar Singh (nickzuck_007)
C#
// A recursive C# program to find
// nth catalan number
using System;

class GFG {

    // A recursive function to find
    // nth catalan number
    static int catalan(int n)
    {
        int res = 0;

        // Base case
        if (n <= 1) {
            return 1;
        }
        for (int i = 0; i < n; i++) {
            res += catalan(i) * catalan(n - i - 1);
        }
        return res;
    }

    // Driver Code
    public static void Main()
    {
        for (int i = 0; i < 10; i++)
            Console.Write(catalan(i) + " ");
    }
}

// This code is contributed by
// nitin mittal.
JavaScript
<script>

// Javascript Program for nth 
// Catalan Number

// A recursive function to
// find nth catalan number
function catalan(n)
{
    
    // Base case
    if (n <= 1)
        return 1;

    // catalan(n) is sum of 
    // catalan(i)*catalan(n-i-1)
    let res = 0;
    for(let i = 0; i < n; i++)
        res += catalan(i) * 
                catalan(n - i - 1);

    return res;
}

// Driver Code
for (let i = 0; i < 10; i++)
    document.write(catalan(i) + " ");

// This code is contributed _saurabh_jaiswal

</script>
PHP
<?php
// PHP Program for nth 
// Catalan Number

// A recursive function to
// find nth catalan number
function catalan($n)
{
    
    // Base case
    if ($n <= 1)
        return 1;

    // catalan(n) is sum of 
    // catalan(i)*catalan(n-i-1)
    $res = 0;
    for($i = 0; $i < $n; $i++)
        $res += catalan($i) * 
                catalan($n - $i - 1);

    return $res;
}

// Driver Code
for ($i = 0; $i < 10; $i++)
    echo catalan($i), " ";

// This code is contributed aj_36
?>

Output
1 1 2 5 14 42 132 429 1430 4862 

Time Complexity: The above implementation is equivalent to nth Catalan number. 

[Tex]T(n)=\sum_{i=0}^{n-1}T(i)*T(n-i-1) \ for \ n\geq 1;                                       [/Tex]

The value of nth Catalan number is exponential which makes the time complexity exponential.
Auxiliary Space: O(n)

Program for nth Catalan Number using Dynamic Programming:

We can observe that the above recursive implementation does a lot of repeated work. Since there are overlapping subproblems, we can use dynamic programming for this.

Step-by-step approach:

  • Create an array catalan[] for storing ith Catalan number.
  • Initialize, catalan[0] and catalan[1] = 1
  • Loop through i = 2 to the given Catalan number n.
    • Loop through j = 0 to j < i and Keep adding value of catalan[j] * catalan[i – j – 1] into catalan[i].
  • Finally, return catalan[n]

Follow the steps below to implement the above approach:

C++
#include <iostream>
using namespace std;

// A dynamic programming based function to find nth
// Catalan number
unsigned long int catalanDP(unsigned int n)
{
    // Table to store results of subproblems
    unsigned long int catalan[n + 1];

    // Initialize first two values in table
    catalan[0] = catalan[1] = 1;

    // Fill entries in catalan[] using recursive formula
    for (int i = 2; i <= n; i++) {
        catalan[i] = 0;
        for (int j = 0; j < i; j++)
            catalan[i] += catalan[j] * catalan[i - j - 1];
    }

    // Return last entry
    return catalan[n];
}

// Driver code
int main()
{
    for (int i = 0; i < 10; i++)
        cout << catalanDP(i) << " ";
    return 0;
}
Java
import java.io.*;
class GFG {

    // A dynamic programming based function to find nth
    // Catalan number
    static int catalanDP(int n)
    {
        // Table to store results of subproblems
        int catalan[] = new int[n + 2];

        // Initialize first two values in table
        catalan[0] = 1;
        catalan[1] = 1;

        // Fill entries in catalan[]
        // using recursive formula
        for (int i = 2; i <= n; i++) {
            catalan[i] = 0;
            for (int j = 0; j < i; j++) {
                catalan[i]
                    += catalan[j] * catalan[i - j - 1];
            }
        }

        // Return last entry
        return catalan[n];
    }

    // Driver code
    public static void main(String[] args)
    {
        for (int i = 0; i < 10; i++) {
            System.out.print(catalanDP(i) + " ");
        }
    }
}
// This code contributed by Rajput-Ji
Python
# A dynamic programming based function to find nth
# Catalan number


def catalan(n):
    if (n == 0 or n == 1):
        return 1

    # Table to store results of subproblems
    catalan = [0]*(n+1)

    # Initialize first two values in table
    catalan[0] = 1
    catalan[1] = 1

    # Fill entries in catalan[]
    # using recursive formula
    for i in range(2, n + 1):
        for j in range(i):
            catalan[i] += catalan[j] * catalan[i-j-1]

    # Return last entry
    return catalan[n]


# Driver code
for i in range(10):
    print(catalan(i), end=" ")
# This code is contributed by Ediga_manisha
C#
using System;

class GFG {

    // A dynamic programming based
    // function to find nth
    // Catalan number
    static uint catalanDP(uint n)
    {
        // Table to store results of subproblems
        uint[] catalan = new uint[n + 2];

        // Initialize first two values in table
        catalan[0] = catalan[1] = 1;

        // Fill entries in catalan[]
        // using recursive formula
        for (uint i = 2; i <= n; i++) {
            catalan[i] = 0;
            for (uint j = 0; j < i; j++)
                catalan[i]
                    += catalan[j] * catalan[i - j - 1];
        }

        // Return last entry
        return catalan[n];
    }

    // Driver code
    static void Main()
    {
        for (uint i = 0; i < 10; i++)
            Console.Write(catalanDP(i) + " ");
    }
}

// This code is contributed by Chandan_jnu
JavaScript
<script>
// Javascript program for nth Catalan Number

// A dynamic programming based function 
// to find nth Catalan number
function catalanDP(n)
{
    
    // Table to store results 
    // of subproblems
    let catalan= [];

    // Initialize first two 
    // values in table
    catalan[0] = catalan[1] = 1;

    // Fill entries in catalan[] 
    // using recursive formula
    for (let i = 2; i <= n; i++)
    {
        catalan[i] = 0;
        for (let j = 0; j < i; j++)
            catalan[i] += catalan[j] * 
                   catalan[i - j - 1];
    }

    // Return last entry
    return catalan[n];
}

    // Driver Code
    for (let i = 0; i < 10; i++)
        document.write(catalanDP(i) + " ");

// This code is contributed _saurabh_jaiswal
</script>
PHP
<?php
// PHP program for nth Catalan Number

// A dynamic programming based function 
// to find nth Catalan number
function catalanDP( $n)
{
    
    // Table to store results 
    // of subproblems
    $catalan= array();

    // Initialize first two 
    // values in table
    $catalan[0] = $catalan[1] = 1;

    // Fill entries in catalan[] 
    // using recursive formula
    for ($i = 2; $i <= $n; $i++)
    {
        $catalan[$i] = 0;
        for ( $j = 0; $j < $i; $j++)
            $catalan[$i] += $catalan[$j] * 
                   $catalan[$i - $j - 1];
    }

    // Return last entry
    return $catalan[$n];
}

    // Driver Code
    for ($i = 0; $i < 10; $i++)
        echo catalanDP($i) , " ";

// This code is contributed anuj_67.
?>

Output
1 1 2 5 14 42 132 429 1430 4862 

Time Complexity: O(n2)
Auxiliary Space: O(n)

Program for nth Catalan Number using Binomial Coefficient:

We can also use the below formula to find nth Catalan number in O(n) time. 

[Tex]C_n=\frac{1}{n+1}\binom{2n}{n}                                         [/Tex]

Here is the proof for the Expression:– 

This is the expression for which we are going to see the proof 

In the pascal triangle,

                           1 
                      1         1
                 1        2        1 
             1       3         3       1 
        1      4         6       4         1
   1     5         10     10       5         1 
 

 Pascal’s triangle as binomial coefficients

the formula for a cell of Pascal’s triangle

Pascal’s triangle

.

.

.

Below are the steps for calculating nCr.

  • Create a variable to store the answer and change r to n – r if r is greater than n – r because we know that C(n, r) = C(n, n-r) if r > n – r 
  • Run a loop from 0 to r-1
    • In every iteration update ans as (ans*(n-i))/(i+1), where i is the loop counter.
  • So the answer will be equal to ((n/1)*((n-1)/2)*…*((n-r+1)/r), which is equal to nCr.

Below are steps to calculate Catalan numbers using the formula: 2nCn/(n+1)

  • Calculate 2nCn using the similar steps that we use to calculate nCr
  • Return the value 2nCn/ (n + 1)

Below is the implementation of the above approach:

C++
// C++ program for nth Catalan Number
#include <iostream>
using namespace std;

// Returns value of Binomial Coefficient C(n, k)
unsigned long int binomialCoeff(unsigned int n,
                                unsigned int k)
{
    unsigned long int res = 1;

    // Since C(n, k) = C(n, n-k)
    if (k > n - k)
        k = n - k;

    // Calculate value of [n*(n-1)*---*(n-k+1)] /
    // [k*(k-1)*---*1]
    for (int i = 0; i < k; ++i) {
        res *= (n - i);
        res /= (i + 1);
    }

    return res;
}

// A Binomial coefficient based function to find nth catalan
// number in O(n) time
unsigned long int catalan(unsigned int n)
{
    // Calculate value of 2nCn
    unsigned long int c = binomialCoeff(2 * n, n);

    // return 2nCn/(n+1)
    return c / (n + 1);
}

// Driver code
int main()
{
    for (int i = 0; i < 10; i++)
        cout << catalan(i) << " ";
    return 0;
}
Java
// Java program for nth Catalan Number

class GFG {

    // Returns value of Binomial Coefficient C(n, k)
    static long binomialCoeff(int n, int k)
    {
        long res = 1;

        // Since C(n, k) = C(n, n-k)
        if (k > n - k) {
            k = n - k;
        }

        // Calculate value of [n*(n-1)*---*(n-k+1)] /
        // [k*(k-1)*---*1]
        for (int i = 0; i < k; ++i) {
            res *= (n - i);
            res /= (i + 1);
        }

        return res;
    }

    // A Binomial coefficient based function
    //  to find nth catalan number in O(n) time
    static long catalan(int n)
    {
        // Calculate value of 2nCn
        long c = binomialCoeff(2 * n, n);

        // return 2nCn/(n+1)
        return c / (n + 1);
    }

    // Driver code
    public static void main(String[] args)
    {
        for (int i = 0; i < 10; i++) {
            System.out.print(catalan(i) + " ");
        }
    }
}
Python
# Python program for nth Catalan Number
# Returns value of Binomial Coefficient C(n, k)


def binomialCoefficient(n, k):

    # since C(n, k) = C(n, n - k)
    if (k > n - k):
        k = n - k

    # initialize result
    res = 1

    # Calculate value of [n * (n-1) *---* (n-k + 1)]
    # / [k * (k-1) *----* 1]
    for i in range(k):
        res = res * (n - i)
        res = res / (i + 1)
    return res

# A Binomial coefficient based function to
# find nth catalan number in O(n) time


def catalan(n):
    c = binomialCoefficient(2*n, n)
    return c/(n + 1)


# Driver Code
for i in range(10):
    print(catalan(i), end=" ")

# This code is contributed by Aditi Sharma
C#
// C# program for nth Catalan Number
using System;
class GFG {

    // Returns value of Binomial Coefficient C(n, k)
    static long binomialCoeff(int n, int k)
    {
        long res = 1;

        // Since C(n, k) = C(n, n-k)
        if (k > n - k) {
            k = n - k;
        }

        // Calculate value of [n*(n-1)*---*(n-k+1)] /
        // [k*(k-1)*---*1]
        for (int i = 0; i < k; ++i) {
            res *= (n - i);
            res /= (i + 1);
        }

        return res;
    }

    // A Binomial coefficient based function to find nth
    // catalan number in O(n) time
    static long catalan(int n)
    {
        // Calculate value of 2nCn
        long c = binomialCoeff(2 * n, n);

        // return 2nCn/(n+1)
        return c / (n + 1);
    }

    // Driver code
    public static void Main()
    {
        for (int i = 0; i < 10; i++) {
            Console.Write(catalan(i) + " ");
        }
    }
}

// This code is contributed
// by Akanksha Rai
JavaScript
<script>
// Javascript program for nth Catalan Number 

// Returns value of Binomial 
// Coefficient C(n, k) 
function binomialCoeff(n, k) 
{ 
    let res = 1; 

    // Since C(n, k) = C(n, n-k) 
    if (k > n - k) 
        k = n - k; 

    // Calculate value of [n*(n-1)*---*(n-k+1)] / 
    //                    [k*(k-1)*---*1] 
    for (let i = 0; i < k; ++i) 
    { 
        res *= (n - i); 
        res = Math.floor(res / (i + 1)); 
    } 

    return res; 
} 

// A Binomial coefficient based function 
// to find nth catalan number in O(n) time 
function catalan(n) 
{ 

    // Calculate value of 2nCn 
    c = binomialCoeff(2 * (n), n); 

    // return 2nCn/(n+1) 
    return Math.floor(c / (n + 1)); 
} 

// Driver code 
for (let i = 0; i < 10; i++) 
document.write(catalan(i) + " " ); 

// This code is contributed by _saurabh_jaiswal
</script>
PHP
<?php
// PHP program for nth Catalan Number 

// Returns value of Binomial 
// Coefficient C(n, k) 
function binomialCoeff($n, $k) 
{ 
    $res = 1; 

    // Since C(n, k) = C(n, n-k) 
    if ($k > $n - $k) 
        $k = $n - $k; 

    // Calculate value of [n*(n-1)*---*(n-k+1)] / 
    //                    [k*(k-1)*---*1] 
    for ($i = 0; $i < $k; ++$i) 
    { 
        $res *= ($n - $i); 
        $res = floor($res / ($i + 1)); 
    } 

    return $res; 
} 

// A Binomial coefficient based function 
// to find nth catalan number in O(n) time 
function catalan($n) 
{ 
    // Calculate value of 2nCn 
    $c = binomialCoeff(2 * ($n), $n); 

    // return 2nCn/(n+1) 
    return floor($c / ($n + 1)); 
} 

// Driver code 
for ($i = 0; $i < 10; $i++) 
echo catalan($i), " " ; 

// This code is contributed by Ryuga
?>

Output
1 1 2 5 14 42 132 429 1430 4862 

Time Complexity: O(n).
Auxiliary Space: O(1)

We can also use the below formulas to find nth Catalan number in O(n) time. 

[Tex]C_n=\frac{(2n)!}{(n+1)!n!}=\prod_{k=2}^{n}\frac{n+k}{k} \ for \ n\geq 0            [/Tex]

[Tex]C_n = \frac{2(2n-1)}{n+1}*C_{n-1} \ \ \  {|} \ \ {n>0} [/Tex]

Program for nth Catalan Number using the (n-1)th Catalan Number:

We already know how to calculate the nth Catalan Number using the below formula, Catalan_1

This formula can be further simplified to express the nth Catalan Number in the terms of (n-1)th Catalan Number,

Catalan_2

Below are steps to calculate Catalan numbers using the above formula:

  • Initialize a variable res = 1
  • Print 1 as the first Catalan Number
  • Iterate from i = 1 to i < n
    • Update res with res = (res * (4 * i – 2)) / (i + 1)
    • print res

Below is the implementation for the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to print first n Catalan numbers
void catalan(int n)
{
    int res = 1;
    cout << res << " ";
    // Iterate till n
    for (int i = 1; i < n; i++) {
        // Calculate the ith Catalan number
        res = (res * (4 * i - 2)) / (i + 1);
           cout << res << " ";
    }
}

// Driver code
int main()
{
    int n = 10;

    // Function call
    catalan(n);
    return 0;
}
Java
import java.util.*;
class GFG {

    // Function to print first n Catalan numbers
    static void catalan(int n)
    {
        int res = 1;
        System.out.print(1 + " ");
        // Iterate till N
        for (int i = 1; i < n; i++) {
            // Calculate the ith Catalan Number
            res = (res * (4 * i - 2)) / (i + 1);
            System.out.print(res + " ");
        }
    }

    // Driver code
    public static void main(String args[])
    {
        int n = 10;

        // Function call
        catalan(n);
    }
}

// This code is contributed by Debojyoti Mandal
Python
# Function to print first n Catalan numbers
def catalan(n):

    res = 1

    print(1, end=" ")
    # Iterate till N
    for i in range(1, n):

        # Calculate the ith Catalan number
        res = (res * (4 * i - 2)) // (i + 1)
        print(res, end=" ")


# Driver code
n = 10

# Function call
catalan(n)

# This code is contributed by rohan07
C#
using System;

public class GFG {

    // Function to print first n Catalan numbers
    static void catalan(int n)
    {
        int res = 1;

        Console.Write(1 + " ");
        // Iterate till N
        for (int i = 1; i < n; i++) {
            // Calculate the ith Catalana Number
            res = (res * (4 * i - 2)) / (i + 1);
            Console.Write(res + " ");
        }
    }

    // Driver code
    public static void Main(String[] args)
    {
        int n = 10;
        // Function call
        catalan(n);
    }
}

// This code is contributed by Rajput-Ji
JavaScript
<script>
    // Function to print first n Catalan numbers
    function catalan(n)
    {
        let res = 1;
        document.write(1 + " ");
        
        // Iterate till N
        for (let i = 1; i < n; i++)
        {
            // Calculate the ith Catalan Number
            res = (res * (4 * i - 2)) / (i + 1);
            document.write(res + " ");
        }
    }
    
    // Driver code
        let n = 10;
    
        // Function call
        catalan(n);
    
    //This code is contributed by Mayank Tyagi
</script>

Output
1 1 2 5 14 42 132 429 1430 4862 

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

 



Previous Article
Next Article

Similar Reads

Program for nth Fuss–Catalan Number
Fuss–Catalan Numbers are a generalization of Catalan numbers that uses triplets instead of pairs. The Fuss-Catalan Numbers can be represented by a Series with the formula: The first few Fuss–Catalan Numbers are 1, 1, 3, 12, 55, 273, 1428, 7752, 43263, 246675...........for n = 0, 1, 2, 3, ... respectively Applications of Fuss-Catalan number: Count t
5 min read
Total number of possible Binary Search Trees using Catalan Number
Given an integer N, the task is to count the number of possible Binary Search Trees with N keys. Examples: Input: N = 2 Output: 2 For N = 2, there are 2 unique BSTs 1 2 \ / 2 1 Input: N = 9 Output: 4862 Approach: The number of binary search trees that will be formed with N keys can be calculated by simply evaluating the corresponding number in Cata
13 min read
Replace every node in Linked list with its closest catalan number
Given a singly linked list, the task is to replace every node with its closest Catalan number. Note: Catalan numbers are defined as mathematical sequence that consists of positive integers, which can be used to find the number of possibilities of various combinations. The first few Catalan numbers are: 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862. Exam
4 min read
Find product of nodes whose weights is catalan number in a Linked list
Given a linked list with weights, the task is to find the product of nodes whose weights are Catalan numbers. Examples: Input: 3(1) -> 7 (4) -> 5 (2) -> 12 (5) -> 14 (3) -> NULLOutput: 180Explanation: Catalan number weights are 1, 2, and 5, and the product of their nodes is 3 * 5 * 12 = 180. Input: 45 (4) -> 21 (2) -> 5 (5) -
11 min read
Minimum changes required to make a Catalan Sequence
Given an array arr[] of N integer elements, the task is to change the minimum number of elements of this array such that it contains first N terms of the Catalan Sequence. Thus, find the minimum changes required.First few Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .....Examples: Input: arr[] = {4, 1, 2, 33, 213, 5} Output: 3 We h
8 min read
GFact | Catalan Numbers
The number of structurally different Binary Trees with n nodes is Catalan number Cn = (2n)!/(n+1)!*n! References: http://mathworld.wolfram.com/BinaryTree.html
1 min read
Applications of Catalan Numbers
Background : Catalan numbers are defined using below formula: [Tex]C_{n} = (2n)!/(n+1)!n! = \prod^{n}_{k=2} \frac{n+k}{k} for_ n >= 0 [/Tex] Catalan numbers can also be defined using following recursive formula. [Tex]C_{0} = 1 C_{n+1} = \sum ^{n} _{i=0} C_{i}C_{n-i} for_ n>=0 [/Tex] The first few Catalan numbers for n = 0, 1, 2, 3, … are 1, 1
3 min read
Program to find the Nth Harmonic Number
Given a number N. The task is to find the Nth Harmonic Number.Let the nth harmonic number be Hn.The harmonic series is as follows: H1 = 1 H2 = H1 + 1/2 H3 = H2 + 1/3 H4 = H3 + 1/4 . . . Hn = Hn-1 + 1/n Examples: Input : N = 5 Output : 2.45 Input : N = 9 Output : 2.71786 The idea is to traverse from H1 and then consecutively keep finding H2 from H1,
6 min read
Program to find the Nth number of the series 2, 10, 24, 44, 70.....
Given a number N, the task is to find the Nth (N may be up to 10^18) term of this series: 2, 10, 24, 44, 70..... The answer can be very large so print answer under modulo 10^9+9. Examples: Input: N = 2 Output: 10 Input: N = 5 Output: 70 Approach:The formula for Nth term will be: Nth term = 3*n*n - n Below is the implementation of the above approach
4 min read
Program to find the Nth Prime Number
Given an integer N. The task is to find the Nth prime number. Examples: Input : 5 Output : 11 Input : 16 Output : 53 Input : 1049 Output : 8377 Approach: Find the prime numbers up to MAX_SIZE using Sieve of Eratosthenes.Store all primes in a vector.For a given number N, return the element at (N-1)th index in a vector. Below is the implementation of
13 min read
Program to find Nth odd Fibonacci Number
Given an integer N. The task is to find the Nth odd Fibonacci number.The odd number fibonacci series is as: 1, 1, 3, 5, 13, 21, 55, 89, 233, 377, 987, 1597.............and so on.Note: In the above series we have omitted even terms from the general fibonacci sequence. Examples: Input: N = 3 Output: 3 Input: N = 4 Output: 5 Approach: On observing car
3 min read
Program to find the Nth natural number with exactly two bits set | Set 2
Given an integer N, the task is to find the Nth natural number with exactly two set bits. Examples: Input: N = 4Output: 9Explanation: Numbers with exactly two set bits are 3, 5, 6, 9, 10, 12, .... The 4th term in this series is 9. Input: N = 15Output: 48Explanation: Numbers with exactly two set bits are 3, 5, 6, 9, 10, 12, 17, 18, 20, 24, 33, 34, 3
7 min read
Program to find the Nth Composite Number
Given a positive integer N, the task is to find the Nth Composite Number. Examples: Input: N = 1Output: 4 Input: N = 3 Output: 8 Approach: The given problem can be solved by using the concept of Sieve of Eratosthenes. Follow the steps below to solve the problem: Mark all the Prime Numbers till 105 in a boolean array say isPrime[] using Sieve of Era
10 min read
Program to find last two digits of Nth Fibonacci number
Given a number ‘n’, write a function that prints the last two digits of n-th (‘n’ can also be a large number) Fibonacci number.Examples: Input : n = 65 Output : 65 Input : n = 365 Output : 65 Recommended: Please solve it on “PRACTICE” first, before moving on to the solution. A simple solution is to find n-th Fibonacci number and print its last two
9 min read
Program to find the nth Kynea number
Given a positive integer n, the task is to find nth Kynea number. Kynea number: In mathematics, a Kynea number is a positive integer of the form: where n is a positive integer.The equivalent formula for nth Kynea number is: The first few Kynea number are: 7, 23, 79, 287, 1087, 4223, 16639, 66047, 263167, 1050623, 4198399, ..... Examples: Input: 2Ou
7 min read
Program to find Nth Hexagonal Number
Given an integer n, the task is to find the nth hexagonal number . The nth hexagonal number Hn is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots when the hexagons are overlaid so that they share one vertex. Input: n = 2Output: 6Input: n = 5Output: 45Input: n = 7Output: 91 In g
3 min read
Find Nth number in a sequence which is not a multiple of a given number
Given four integers A, N, L and R, the task is to find the N th number in a sequence of consecutive integers from L to R which is not a multiple of A. It is given that the sequence contain at least N numbers which are not divisible by A and the integer A is always greater than 1. Examples: Input: A = 2, N = 3, L = 1, R = 10 Output: 5 Explanation: T
9 min read
Number of digits in the nth number made of given four digits
Find the number of digits in the nth number constructed by using 6, 1, 4, and 9 as the only digits in the ascending order. First few numbers constructed by using only 6, 1, 4, and 9 as digits in ascending order would be: 1, 6, 4, 9, 11, 14, 16, 19, 41, 44, 46, 49, 61, 64, 66, 69, 91, 94, 96, 99, 111, 114, 116, 119 and so on. Examples: Input : 6Outp
13 min read
Program to get the Sum of series: 1 - x^2/2! + x^4/4! -.... upto nth term
This is a mathematical series program where a user must enter the number of terms up to which the sum of the series is to be found. Following this, we also need the value of x, which forms the base of the series. Examples: Input : x = 9, n = 10 Output : -5.1463 Input : x = 5, n = 15 Output : 0.2837 Simple approach : We use two nested loops to compu
10 min read
Program to find Nth term of series 1, 3, 12, 60, 360…
Given a number N. The task is to write a program to find the Nth term in the below series: 1, 3, 12, 60, 360… Examples: Input: 2 Output: 3 Input: 4 Output: 60 Approach: The idea is to first find the factorial of the number (N+1), that is (N+1)!Now, the N-th term in the above series will be: N-th term = (N+1)!/2 Below is the implementation of the ab
5 min read
Program to find the Nth term of series -1, 2, 11, 26, 47......
Given a number N, the task is to find the Nth term of this series: -1, 2, 11, 26, 47, 74, ..... Examples: Input: 3 Output: 11 Explanation: when N = 3 Nth term = ( (3 * N * N) - (6 * N) + 2 ) = ( (3 * 3 * 3) - (6 * 3) + 2 ) = 11 Input: 9 Output: 191 Approach: The Nth term of the given series can be generalised as: Nth term of the series : ( (3 * N *
3 min read
Program to print tetrahedral numbers upto Nth term
Prerequisites: Triangular numbersTetrahedral numbers Given a value n, and the task is to print tetrahedral number series up to nth term.Examples: Input: 5 Output: 1 4 10 20 35 Input: 10 Output: 1 4 10 20 35 56 84 120 165 220 Method 1: Using Triangular Number series: This problem can be easily solved with the fact that Nth Tetrahedral Number is equa
9 min read
Program to print pentatope numbers upto Nth term
Prerequisites: Tetrahedral numbersPentatope Numbers Given a value n, and the task is to print pentatope numbers series up to nth term.Examples: Input: 5 Output: 1 5 15 35 70 Input: 10 Output: 1 5 15 35 70 126 210 330 495 715 Method 1: Using Tetrahedral Number Series: This problem can be easily solved with the fact that Nth Pentatope Number is equal
10 min read
Program to find Nth term of series 9, 23, 45, 75, 113...
Given a number N, the task is to find the Nth term in the given series: 9, 23, 45, 75, 113, 159...... Examples: Input: 4 Output: 113 Explanation: For N = 4 Nth term = ( 2 * N + 3 )*( 2 * N + 3 ) - 2 * N = ( 2 * 4 + 3 )*( 2 * 4 + 3 ) - 2 * 4 = 113 Input: 10 Output: 509 Approach: The Nth term of the given series can be generalised as: Nth term of the
4 min read
Program to find Nth term in the series 0, 2, 1, 3, 1, 5, 2, 7, 3,…
Given a number N. The task is to write a program to find the N-th term in the below series: 0, 2, 1, 3, 1, 5, 2, 7, 3, … Examples: Input: N = 5 Output: 1 Input: N = 10 Output: 11 When we look carefully at the series, we find that the series is a mixture of 2 series: Terms at odd positions in the given series forms fibonacci series.Terms at even pos
8 min read
Program to find the Nth term of the series 3, 20, 63, 144, 230, ……
Given a series and a number N. The task is to find the Nth term of the given series: 3, 20, 63, 144, 230 ..... Examples: Input: N = 4 Output: 144 When n = 4 nth term = 2 ( n * n * n ) + n * n = 2 ( 4 * 4 * 4 ) + 4 * 4 = 144 Input: N = 10 Output: 2100 Approach: We can find the general term (Tn) of the given series. [Tex]series\: can\: be\: written\:
3 min read
Program to find the Nth term of series 5, 10, 17, 26, 37, 50, 65, 82, ...
Given a number N. The task is to write a program to find the Nth term of the below series: 5, 10, 17, 26, 37, 50, 65, 82, ...(N Terms) Examples: Input: N = 4 Output: 82 For N = 4 4th Term = ( 4 * 4 + 2 * 4 + 2) = 26 Input: N = 10 Output: 122 Approach: The generalized Nth term of this series: [Tex]nth\: Term\: of\: the\: series\: = n^2+2n+2[/Tex] Be
3 min read
Program to find the Nth term of series 0, 4, 14, 30, 51, 80, 114, 154, 200, ...
Given a number N. The task is to write a program to find the Nth term of the below series: 0, 4, 14, 30, 51, 80, 114, 154, 200, …(N Terms) Examples: Input: N = 4 Output: 82 For N = 4 4th Term = ( 4 * 4 - 2 * 4 + 2) = 10 Input: N = 10 Output: 122 Approach: The generalized Nth term of this series: [Tex]nth\: Term\: of\: the\: series\: = n^2-2n+2[/Tex
3 min read
Program to find the Nth term of the series 0, 14, 40, 78, 124, ...
Given a number N. The task is to write a program to find the Nth term of the below series: 0, 14, 40, 78, 124 ...(N Terms) Examples: Input: N = 4 Output: 78 For N = 4 Sum(upto 4 terms) = ( 6 * n * n - 4 * n - 2) = ( 6 * 4 * 4 - 4 * 4 - 2) = 78 Input: N = 10 Output: 557 Approach: The generalized Nth term of this series:[Tex]nth\: Term\: of\: the\: s
3 min read
Program to find the Nth term of the series 0, 5, 14, 27, 44, ........
Given a number N. The task is to write a program to find the Nth term in the below series: 0, 5, 14, 27, 44 ...(Nth Term) Examples: Input: N = 4 Output: 27 For N = 4, Nth term = ( 2 * N * N - N - 1 ) = ( 2 * 4 * 4 - 4 - 1 ) = 27 Input: N = 10 Output: 188 Approach: The generalized Nth term of this series: Nth Term: 2 * N * N - N - 1 Below is the req
3 min read
three90RightbarBannerImg