{"id":27218,"date":"2018-01-03T22:23:01","date_gmt":"2018-01-03T16:53:01","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27218"},"modified":"2018-01-03T22:23:01","modified_gmt":"2018-01-03T16:53:01","slug":"java-programming-count-n-digit-numbers-whose-sum-digits-equals-given-sum","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-count-n-digit-numbers-whose-sum-digits-equals-given-sum\/","title":{"rendered":"Java Programming &#8211; Count of n digit numbers whose sum of digits equals to given sum"},"content":{"rendered":"<p>Given two integers \u2018n\u2019 and \u2018sum\u2019, find count of all n digit numbers with sum of digits as \u2018sum\u2019. Leading 0\u2019s are not counted as digits.<br \/>\n1 &lt;= n &lt;= 100 and 1 &lt;= sum &lt;= 50000<span id=\"more-135347\"><\/span><\/p>\n<p>Example:<\/p>\n<pre>Input:  n = 2, sum = 2\r\nOutput: 2\r\nExplanation: Numbers are 11 and 20\r\n\r\nInput:  n = 2, sum = 5\r\nOutput: 5\r\nExplanation: Numbers are 14, 23, 32, 41 and 50\r\n\r\nInput:  n = 3, sum = 6\r\nOutput: 21<\/pre>\n<p>The idea is simple, we subtract all values from 0 to 9 from given sum and recur for sum minus that digit. Below is recursive formula.<\/p>\n<pre>    countRec(n, sum) = \u2211countRec(n-1, sum-x)\r\n                            where 0 =&lt; x &lt;= 9 and\r\n                                 sum-x &gt;= 0\r\n\r\n    One important observation is, leading 0's must be\r\n    handled explicitly as they are not counted as digits.\r\n    So our final count can be written as below.\r\n    finalCount(n, sum) = \u2211countRec(n-1, sum-x)\r\n                           where 1 =&lt; x &lt;= 9 and\r\n                                 sum-x &gt;= 0<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p>Below is a simple recursive solution based on above recursive formula.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class sum_dig<br\/>{<br\/>    \/\/ Recursive function to count &#039;n&#039; digit numbers<br\/>    \/\/ with sum of digits as &#039;sum&#039;. This function<br\/>    \/\/ considers leading 0&#039;s also as digits, that is<br\/>    \/\/ why not directly called<br\/>    static int countRec(int n, int sum)<br\/>    {<br\/>        \/\/ Base case<br\/>        if (n == 0)<br\/>           return sum == 0 ?1:0;<br\/>      <br\/>        \/\/ Initialize answer<br\/>        int ans = 0;<br\/>      <br\/>        \/\/ Traverse through every digit and count<br\/>        \/\/ numbers beginning with it using recursion<br\/>        for (int i=0; i&lt;=9; i++)<br\/>           if (sum-i &gt;= 0)<br\/>              ans += countRec(n-1, sum-i);<br\/>      <br\/>        return ans;<br\/>    }<br\/>      <br\/>    \/\/ This is mainly a wrapper over countRec. It<br\/>    \/\/ explicitly handles leading digit and calls<br\/>    \/\/ countRec() for remaining digits.<br\/>    static int finalCount(int n, int sum)<br\/>    {<br\/>        \/\/ Initialize final answer<br\/>        int ans = 0;<br\/>      <br\/>        \/\/ Traverse through every digit from 1 to<br\/>        \/\/ 9 and count numbers beginning with it<br\/>        for (int i = 1; i &lt;= 9; i++)<br\/>          if (sum-i &gt;= 0)<br\/>             ans += countRec(n-1, sum-i);<br\/>      <br\/>        return ans;<br\/>    }<br\/> <br\/>    \/* Driver program to test above function *\/<br\/>    public static void main (String args[])<br\/>    {<br\/>          int n = 2, sum = 5;<br\/>          System.out.println(finalCount(n, sum));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>5<\/pre>\n<p>The time complexity of above solution is exponential. If we draw the complete recursion tree, we can observer that many subproblems are solved again and again. For example, if we start with n = 3 and sum = 10, we can reach n = 1, sum = 8, by considering digit sequences 1,1 or 2, 0.<br \/>\nSince same suproblems are called again, this problem has Overlapping Subprolems property. So min square sum problem has both properties of a dynamic programming problem.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Below is Memoization based the implementation.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class sum_dig<br\/>{<br\/>    \/\/ A lookup table used for memoization<br\/>    static int lookup[][] = new int[101][50001];<br\/>      <br\/>    \/\/ Memoizatiob based implementation of recursive<br\/>    \/\/ function<br\/>    static int countRec(int n, int sum)<br\/>    {<br\/>        \/\/ Base case<br\/>        if (n == 0)<br\/>           return sum == 0 ? 1 : 0;<br\/>      <br\/>        \/\/ If this subproblem is already evaluated,<br\/>        \/\/ return the evaluated value<br\/>        if (lookup[n][sum] != -1)<br\/>           return lookup[n][sum];<br\/>      <br\/>        \/\/ Initialize answer<br\/>        int ans = 0;<br\/>      <br\/>        \/\/ Traverse through every digit and<br\/>        \/\/ recursively count numbers beginning<br\/>        \/\/ with it<br\/>        for (int i=0; i&lt;10; i++)<br\/>           if (sum-i &gt;= 0)<br\/>              ans += countRec(n-1, sum-i);<br\/>      <br\/>        return lookup[n][sum] = ans;<br\/>    }<br\/>      <br\/>    \/\/ This is mainly a wrapper over countRec. It<br\/>    \/\/ explicitly handles leading digit and calls<br\/>    \/\/ countRec() for remaining n.<br\/>    static int finalCount(int n, int sum)<br\/>    {<br\/>        \/\/ Initialize all entries of lookup table<br\/>        for(int i = 0;i&lt;=100;++i){<br\/>            for(int j=0;j&lt;=50000;++j){<br\/>                lookup[i][j] = -1;<br\/>            }<br\/>        }<br\/>      <br\/>        \/\/ Initialize final answer<br\/>        int ans = 0;<br\/>      <br\/>        \/\/ Traverse through every digit from 1 to<br\/>        \/\/ 9 and count numbers beginning with it<br\/>        for (int i = 1; i &lt;= 9; i++)<br\/>          if (sum-i &gt;= 0)<br\/>             ans += countRec(n-1, sum-i);<br\/>        return ans;<br\/>    }<br\/> <br\/>    \/* Driver program to test above function *\/<br\/>    public static void main (String args[])<br\/>    {<br\/>          int n = 2, sum = 5;<br\/>          System.out.println(finalCount(n, sum));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>5<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Programming &#8211; Count of n digit numbers whose sum of digits equals to given sum &#8211; Dynamic Programming Given two integers \u2018n\u2019 and \u2018sum\u2019, find count<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,70145,2139],"tags":[81124,81122,81123,72842,72846,72850,72839,81132,81128,81119,72852,81131,72855,81129],"class_list":["post-27218","post","type-post","status-publish","format-standard","hentry","category-coding","category-dynamic-programming","category-java","tag-a-problem-from-a-programming-competition","tag-advanced-algorithms-practice-problems","tag-count-of-numbers-between-a-and-b-inclusive-that-have-sum-of-digits","tag-define-dynamic-programming","tag-dynamic-programming-in-data-structure","tag-explain-dynamic-programming","tag-how-to-solve-dynamic-programming-problems","tag-number-of-occurrences-of-the-digit-1-in-the-numbers-from-0-to-n","tag-numbers-of-length-n-and-value-less-than-k","tag-print-all-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum","tag-problems-on-dynamic-programming","tag-program-to-find-sum-of-digits-of-a-number-in-c","tag-simple-dynamic-programming-example","tag-sum-of-digits-from-1-to-100"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27218","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\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27218"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27218\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27218"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27218"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27218"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}