{"id":26118,"date":"2017-10-26T19:59:19","date_gmt":"2017-10-26T14:29:19","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26118"},"modified":"2017-10-26T19:59:19","modified_gmt":"2017-10-26T14:29:19","slug":"c-programming-program-nth-catalan-number","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-program-nth-catalan-number\/","title":{"rendered":"C++ Programming &#8211; Program for nth Catalan Number"},"content":{"rendered":"<p>Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like following.<span id=\"more-129065\"><\/span><\/p>\n<p><strong>1)<\/strong> Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).<\/p>\n<p><strong>2)<\/strong> Count the number of possible Binary Search Trees with n keys (See <a href=\"http:\/\/www.geeksforgeeks.org\/g-fact-18\/\" target=\"_blank\" rel=\"noopener noreferrer\">this<\/a>)<\/p>\n<p><strong>3)<\/strong> 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.<\/p>\n<p>The first few Catalan numbers for n = 0, 1, 2, 3, \u2026 are <strong>1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, \u2026<\/strong><\/p>\n<p><strong>Recursive Solution<\/strong><br \/>\nCatalan numbers satisfy the following recursive formula.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26122\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/catalan.png\" alt=\"catalan\" width=\"375\" height=\"19\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/catalan.png 375w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/catalan-300x15.png 300w\" sizes=\"(max-width: 375px) 100vw, 375px\" \/><\/p>\n<p>Following is the implementation of above recursive formula.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">#include&lt;iostream&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ A recursive function to find nth catalan number<br\/>unsigned long int catalan(unsigned int n)<br\/>{<br\/>    \/\/ Base case<br\/>    if (n &lt;= 1) return 1;<br\/> <br\/>    \/\/ catalan(n) is sum of catalan(i)*catalan(n-i-1)<br\/>    unsigned long int res = 0;<br\/>    for (int i=0; i&lt;n; i++)<br\/>        res += catalan(i)*catalan(n-i-1);<br\/> <br\/>    return res;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main()<br\/>{<br\/>    for (int i=0; i&lt;10; i++)<br\/>        cout &lt;&lt; catalan(i) &lt;&lt; &quot; &quot;;<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>&nbsp;<\/p>\n<p><strong>Output :<\/strong><\/p>\n<pre>1 1 2 5 14 42 132 429 1430 4862<\/pre>\n<p>The value of nth catalan number is exponential that makes the time complexity exponential.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Dynamic Programming Solution<\/strong><br \/>\nWe can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing recursion tree). Since there are overlapping subproblems, we can use dynamic programming for this. Following is a Dynamic programming based implementation in C++.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++ Program <\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">#include&lt;iostream&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ A dynamic programming based function to find nth<br\/>\/\/ Catalan number<br\/>unsigned long int catalanDP(unsigned int n)<br\/>{<br\/>    \/\/ Table to store results of subproblems<br\/>    unsigned long int catalan[n+1];<br\/> <br\/>    \/\/ Initialize first two values in table<br\/>    catalan[0] = catalan[1] = 1;<br\/> <br\/>    \/\/ Fill entries in catalan[] using recursive formula<br\/>    for (int i=2; i&lt;=n; i++)<br\/>    {<br\/>        catalan[i] = 0;<br\/>        for (int j=0; j&lt;i; j++)<br\/>            catalan[i] += catalan[j] * catalan[i-j-1];<br\/>    }<br\/> <br\/>    \/\/ Return last entry<br\/>    return catalan[n];<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main()<br\/>{<br\/>    for (int i = 0; i &lt; 10; i++)<br\/>        cout &lt;&lt; catalanDP(i) &lt;&lt; &quot; &quot;;<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>1 1 2 5 14 42 132 429 1430 4862<\/pre>\n<p>Time Complexity: Time complexity of above implementation is O(n<sup>2<\/sup>)<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Using Binomial Coefficient <\/strong><br \/>\nWe can also use the below formula to find nth catalan number in O(n) time.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++ Program<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">#include&lt;iostream&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ Returns value of Binomial Coefficient C(n, k)<br\/>unsigned long int binomialCoeff(unsigned int n, unsigned int k)<br\/>{<br\/>    unsigned long int res = 1;<br\/> <br\/>    \/\/ Since C(n, k) = C(n, n-k)<br\/>    if (k &gt; n - k)<br\/>        k = n - k;<br\/> <br\/>    \/\/ Calculate value of [n*(n-1)*---*(n-k+1)] \/ [k*(k-1)*---*1]<br\/>    for (int i = 0; i &lt; k; ++i)<br\/>    {<br\/>        res *= (n - i);<br\/>        res \/= (i + 1);<br\/>    }<br\/> <br\/>    return res;<br\/>}<br\/> <br\/>\/\/ A Binomial coefficient based function to find nth catalan<br\/>\/\/ number in O(n) time<br\/>unsigned long int catalan(unsigned int n)<br\/>{<br\/>    \/\/ Calculate value of 2nCn<br\/>    unsigned long int c = binomialCoeff(2*n, n);<br\/> <br\/>    \/\/ return 2nCn\/(n+1)<br\/>    return c\/(n+1);<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    for (int i = 0; i &lt; 10; i++)<br\/>        cout &lt;&lt; catalan(i) &lt;&lt; &quot; &quot;;<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>1 1 2 5 14 42 132 429 1430 4862<\/pre>\n<p>Time Complexity: Time complexity of above implementation is O(n).<\/p>\n<p>We can also use below formula to find nth catalan number in O(n) time.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ Programming Program for nth Catalan Number &#8211; Mathematical Algorithms &#8211; Catalan numbers are a sequence of natural numbers that occurs in many interesting<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,83515,1,74058],"tags":[77217,77233,77126,77211,77225,77241,77206,77216,77224,77227,77223,77198,77240,77232,77215,77222,77213,77199,77235,77228,77209,77237,77219,77234,77230,77201,77218,77208,77214,77243,77229,77226,77238,77221,77205,77204,77203,77242,77197,77210,77236,77220,77200,73686,70398,77239,77207,77212,77231,77202],"class_list":["post-26118","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-c-programming-3","category-coding","category-mathematical-algorithms","tag-0-1-1-2","tag-1-2-5","tag-1-2-5-14","tag-1-2-of-5","tag-1-in","tag-1-number","tag-14-42","tag-2-5-1","tag-5-14","tag-armstrong-number-wiki","tag-c-n","tag-catalan","tag-catalan-meaning","tag-catalan-numbers","tag-catalan-series","tag-catalana","tag-cn-formula","tag-cn-meaning","tag-convex-hexagon","tag-convex-octagon","tag-de-catalon","tag-define-admissible","tag-define-convex-polygon","tag-define-rigged","tag-discrete-mathematics-recurrence-relations-and-generating-functions","tag-expression-number","tag-factors-of-42-in-pairs","tag-fine-number","tag-handshake-problem-formula","tag-hasse-diagram-example-problems","tag-i-2-pill","tag-mountain-range-definition","tag-narcissistic-number","tag-natural-numbers-wiki","tag-number","tag-number-2","tag-number-expression","tag-number-of-diagonals-formula","tag-number-relation-problems-with-solutions","tag-pair-of-parentheses","tag-parenthesis-example","tag-prime-factors-of-132","tag-q-maths","tag-recursion-in-python","tag-recursive-formula","tag-simple-tree","tag-square-root-of-132","tag-squared-5","tag-well-formed-formula-in-discrete-mathematics","tag-xiv-in-numbers"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26118","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26118"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26118\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26118"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26118"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26118"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}