Number of ways a convex polygon of n+2 sides can split into triangles by connecting vertices
Given a convex polygon with n+2 sides. The task is to calculate the number of ways in which triangles can be formed by connecting vertices with non-crossing line segments.
Examples:
Input: n = 1
Output: 1
It is already a triangle so it can only be formed in 1 way.
Input: n = 2
Output: 2
It can be cut into 2 triangles by using either pair of opposite vertices.
The above problem is an application of a catalan numbers. So, the task is to only find the n’th Catalan Number. First few catalan numbers are 1 1 2 5 14 42 132 429 1430 4862, … (considered from 0th number)
Below is the program to find Nth catalan number:
C++
#include <bits/stdc++.h>
using namespace std;
unsigned long int binomialCoeff(unsigned int n,
unsigned int k)
{
unsigned long int res = 1;
if (k > n - k)
k = n - k;
for ( int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
unsigned long int catalan(unsigned int n)
{
unsigned long int c = binomialCoeff(2 * n, n);
return c / (n + 1);
}
int main()
{
int n = 3;
cout << catalan(n) << endl;
return 0;
}
|
Java
class GFG
{
static long binomialCoeff( int n,
int k)
{
long res = 1 ;
if (k > n - k)
k = n - k;
for ( int i = 0 ; i < k; ++i)
{
res *= (n - i);
res /= (i + 1 );
}
return res;
}
static long catalan( int n)
{
long c = binomialCoeff( 2 * n, n);
return c / (n + 1 );
}
public static void main(String[] args)
{
int n = 3 ;
System.out.println(catalan(n));
}
}
|
Python3
def binomialCoeff(n, k):
res = 1 ;
if (k > n - k):
k = n - k;
for i in range (k):
res * = (n - i);
res / = (i + 1 );
return res;
def catalan(n):
c = binomialCoeff( 2 * n, n);
return int (c / (n + 1 ));
n = 3 ;
print (catalan(n));
|
C#
using System;
class GFG
{
static long binomialCoeff( int n,
int k)
{
long res = 1;
if (k > n - k)
k = n - k;
for ( int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
static long catalan( int n)
{
long c = binomialCoeff(2 * n, n);
return c / (n + 1);
}
public static void Main()
{
int n = 3;
Console.WriteLine(catalan(n));
}
}
|
PHP
<?php
function binomialCoeff( $n , $k )
{
$res = 1;
if ( $k > $n - $k )
$k = $n - $k ;
for ( $i = 0; $i < $k ; ++ $i )
{
$res *= ( $n - $i );
$res /= ( $i + 1);
}
return $res ;
}
function catalan( $n )
{
$c = binomialCoeff(2 * $n , $n );
return $c / ( $n + 1);
}
$n = 3;
echo catalan( $n );
?>
|
Javascript
<script>
function binomialCoeff(n, k)
{
var res = 1;
if (k > n - k)
k = n - k;
for (i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
function catalan(n)
{
var c = binomialCoeff(2 * n, n);
return c / (n + 1);
}
var n = 3;
document.write(catalan(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
01 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...