Count distinct regular bracket sequences which are not N periodic | C ++ program for the above approach ; Function that finds the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Return the C ( n , k ) ; Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; Return C ( 2 n , n ) / ( n + 1 ) ; Function to find possible ways to put balanced parenthesis in an expression of length n ; If n is odd , not possible to create any valid parentheses ; Otherwise return n / 2 th Catalan Number ; Difference between counting ways of 2 * N and N is the result ; Driver Code ; Given value of N ; Function Call
#include <bits/stdc++.h> NEW_LINE 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 ) ; } unsigned long int findWays ( unsigned n ) { if ( n & 1 ) return 0 ; return catalan ( n / 2 ) ; } void countNonNPeriodic ( int N ) { cout << findWays ( 2 * N ) - findWays ( N ) ; } int main ( ) { int N = 4 ; countNonNPeriodic ( N ) ; return 0 ; }