Print all n-digit numbers whose sum of digits equals to given sum - GeeksforGeeks

20 Feb, 2022
Given number of digits n, print all n-digit numbers whose sum of digits adds upto given sum. Solution should not consider leading 0’s as digits.Examples:  
Input:  N = 2, Sum = 3
Output:  12 21 30

Input:  N = 3, Sum = 6
Output:  105 114 123 132 141 150 204 
         213 222 231 240 303 312 321 
         330 402 411 420 501 510 600 

Input:  N = 4, Sum = 3
Output:  1002 1011 1020 1101 1110 1200
         2001 2010 2100 3000 
 
A simple solution would be to generate all N-digit numbers and print numbers that have sum of their digits equal to given sum. The complexity of this solution would be exponential. A better solution is to generate only those N-digit numbers that satisfy the given constraints. The idea is to use recursion. We basically fill all digits from 0 to 9 into current position and maintain sum of digits so far. We then recurse for remaining sum and number of digits left. We handle leading 0’s separately as they are not counted as digits.Below is a simple recursive implementation of above idea – 
C++
Java
Python 3
C#
PHP
Javascript
// A C++ recursive program to print all n-digit// numbers whose sum of digits equals to given sum#include <bits/stdc++.h>using namespace std; // Recursive function to print all n-digit numbers// whose sum of digits equals to given sum // n, sum --> value of inputs// out --> output array// index --> index of next digit to be filled in//           output arrayvoid findNDigitNumsUtil(int n, int sum, char* out,                        int index){    // Base case    if (index > n || sum < 0)        return;     // If number becomes N-digit    if (index == n)    {        // if sum of its digits is equal to given sum,        // print it        if(sum == 0)        {            out[index] = '\0';            cout << out << " ";        }        return;    }     // Traverse through every digit. Note that    // here we're considering leading 0's as digits    for (int i = 0; i <= 9; i++)    {        // append current digit to number        out[index] = i + '0';         // recurse for next digit with reduced sum        findNDigitNumsUtil(n, sum - i, out, index + 1);    }} // This is mainly a wrapper over findNDigitNumsUtil.// It explicitly handles leading digitvoid findNDigitNums(int n, int sum){    // output array to store N-digit numbers    char out[n + 1];     // fill 1st position by every digit from 1 to 9 and    // calls findNDigitNumsUtil() for remaining positions    for (int i = 1; i <= 9; i++)    {        out[0] = i + '0';        findNDigitNumsUtil(n, sum - i, out, 1);    }} // Driver programint main(){    int n = 2, sum = 3;     findNDigitNums(n, sum);     return 0;}
// Java recursive program to print all n-digit// numbers whose sum of digits equals to given sumimport java.io.*; class GFG{    // Recursive function to print all n-digit numbers    // whose sum of digits equals to given sum      // n, sum --> value of inputs    // out --> output array    // index --> index of next digit to be    // filled in output array    static void findNDigitNumsUtil(int n, int sum, char out[],                                   int index)    {        // Base case        if (index > n || sum < 0)            return;          // If number becomes N-digit        if (index == n)        {            // if sum of its digits is equal to given sum,            // print it            if(sum == 0)            {                out[index] = '\0'   ;                System.out.print(out);                System.out.print(" ");            }            return;        }          // Traverse through every digit. Note that        // here we're considering leading 0's as digits        for (int i = 0; i <= 9; i++)        {            // append current digit to number            out[index] = (char)(i + '0');              // recurse for next digit with reduced sum            findNDigitNumsUtil(n, sum - i, out, index + 1);        }    }         // This is mainly a wrapper over findNDigitNumsUtil.    // It explicitly handles leading digit    static void findNDigitNums(int n, int sum)    {        // output array to store N-digit numbers        char[] out = new char[n + 1];          // fill 1st position by every digit from 1 to 9 and        // calls findNDigitNumsUtil() for remaining positions        for (int i = 1; i <= 9; i++)        {            out[0] = (char)(i + '0');            findNDigitNumsUtil(n, sum - i, out, 1);        }    }         // driver program to test above function    public static void main (String[] args)    {             int n = 2, sum = 3;             findNDigitNums(n, sum);    }} // This code is contributed by Pramod Kumar
# Python 3 recursive program to print# all n-digit numbers whose sum of# digits equals to given sum # Recursive function to print all# n-digit numbers whose sum of# digits equals to given sum # n, sum --> value of inputs# out --> output array# index --> index of next digit to be#            filled in output arraydef findNDigitNumsUtil(n, sum, out,index):     # Base case    if (index > n or sum < 0):        return     f = ""         # If number becomes N-digit    if (index == n):             # if sum of its digits is equal        # to given sum, print it        if(sum == 0):            out[index] = "\0"                         for i in out:                f = f + i            print(f, end = " ")                 return     # Traverse through every digit. Note    # that here we're considering leading    # 0's as digits    for i in range(10):                 # append current digit to number        out[index] = chr(i + ord('0'))         # recurse for next digit with reduced sum        findNDigitNumsUtil(n, sum - i,                           out, index + 1) # This is mainly a wrapper over findNDigitNumsUtil.# It explicitly handles leading digitdef findNDigitNums( n, sum):     # output array to store N-digit numbers    out = [False] * (n + 1)     # fill 1st position by every digit    # from 1 to 9 and calls findNDigitNumsUtil()    # for remaining positions    for i in range(1, 10):        out[0] = chr(i + ord('0'))        findNDigitNumsUtil(n, sum - i, out, 1) # Driver Codeif __name__ == "__main__":    n = 2    sum = 3     findNDigitNums(n, sum) # This code is contributed# by ChitraNayal
// C# recursive program to print all n-digit// numbers whose sum of digits equals to// given sumusing System; class GFG {         // Recursive function to print all n-digit    // numbers whose sum of digits equals to    // given sum     // n, sum --> value of inputs    // out --> output array    // index --> index of next digit to be    // filled in output array    static void findNDigitNumsUtil(int n, int sum,                             char []ou, int index)    {        // Base case        if (index > n || sum < 0)            return;         // If number becomes N-digit        if (index == n)        {            // if sum of its digits is equal to            // given sum, print it            if(sum == 0)            {                ou[index] = '\0';                Console.Write(ou);                Console.Write(" ");            }                         return;        }         // Traverse through every digit. Note        // that here we're considering leading        // 0's as digits        for (int i = 0; i <= 9; i++)        {            // append current digit to number            ou[index] = (char)(i + '0');             // recurse for next digit with            // reduced sum            findNDigitNumsUtil(n, sum - i, ou,                                    index + 1);                 }    }     // This is mainly a wrapper over    // findNDigitNumsUtil. It explicitly    // handles leading digit    static void findNDigitNums(int n, int sum)    {                 // output array to store N-digit        // numbers        char []ou = new char[n + 1];         // fill 1st position by every digit        // from 1 to 9 and calls        // findNDigitNumsUtil() for remaining        // positions        for (int i = 1; i <= 9; i++)        {            ou[0] = (char)(i + '0');            findNDigitNumsUtil(n, sum - i, ou, 1);        }    }         // driver program to test above function    public static void Main ()    {            int n = 2, sum = 3;                         findNDigitNums(n, sum);    }} // This code is contributed by nitin mittal.
<?php// A PHP recursive program to print all// n-digit numbers whose sum of digits// equals to given sum // Recursive function to print all n-digit// numbers whose sum of digits equals to// given sum // n, sum --> value of inputs// out --> output array// index --> index of next digit to be//             filled in output arrayfunction findNDigitNumsUtil($n, $sum, $out,                                    $index){    // Base case    if ($index > $n || $sum < 0)        return;     // If number becomes N-digit    if ($index == $n)    {        // if sum of its digits is equal        // to given sum, print it        if($sum == 0)        {            $out[$index] = '';            foreach ($out as &$value)            print($value);            print(" ");        }        return;    }     // Traverse through every digit. Note    // that here we're considering leading    // 0's as digits    for ($i = 0; $i <= 9; $i++)    {        // append current digit to number        $out[$index] = chr($i + ord('0'));         // recurse for next digit with        // reduced sum        findNDigitNumsUtil($n, $sum - $i,                           $out, $index + 1);    }} // This is mainly a wrapper over findNDigitNumsUtil.// It explicitly handles leading digitfunction findNDigitNums($n, $sum){    // output array to store N-digit numbers    $out = array_fill(0, $n + 1, false);     // fill 1st position by every digit from    // 1 to 9 and calls findNDigitNumsUtil()    // for remaining positions    for ($i = 1; $i <= 9; $i++)    {        $out[0] = chr($i + ord('0'));        findNDigitNumsUtil($n, $sum - $i, $out, 1);    }} // Driver Code$n = 2;$sum = 3; findNDigitNums($n, $sum); // This code is contributed// by chandan_jnu?>
<script> // Javascript recursive program to print all n-digit// numbers whose sum of digits equals to given sum         // Recursive function to print all n-digit numbers    // whose sum of digits equals to given sum        // n, sum --> value of inputs    // out --> output array    // index --> index of next digit to be    // filled in output array    function findNDigitNumsUtil(n, sum, out, index)    {             // Base case        if (index > n || sum < 0)            return;            // If number becomes N-digit        if (index == n)        {                     // if sum of its digits is equal to given sum,            // print it            if(sum == 0)            {                out[index] = '\0';                for(let i = 0; i < out.length; i++)                                     document.write(out[i]);                document.write(" ");            }            return;        }            // Traverse through every digit. Note that        // here we're considering leading 0's as digits        for (let i = 0; i <= 9; i++)        {            // append current digit to number            out[index] = String.fromCharCode(i + '0'.charCodeAt(0));                // recurse for next digit with reduced sum            findNDigitNumsUtil(n, sum - i, out, index + 1);        }    }         // This is mainly a wrapper over findNDigitNumsUtil.    // It explicitly handles leading digit    function findNDigitNums(n,sum)    {        // output array to store N-digit numbers        let out = new Array(n+1);        for(let i=0;i<n+1;i++)        {            out[i]=false;        }        // fill 1st position by every digit from 1 to 9 and        // calls findNDigitNumsUtil() for remaining positions        for (let i = 1; i <= 9; i++)        {            out[0] = String.fromCharCode(i + '0'.charCodeAt(0));            findNDigitNumsUtil(n, sum - i, out, 1);        }    }         // driver program to test above function    let  n = 2, sum = 3;    findNDigitNums(n, sum);         // This code is contributed by avanitrachhadiya2155</script>
Output:  
12 21 30 
Time Complexity: O(n*n!)
Auxiliary Space: O(n)
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
ukasp
Chandan_Kumar
mv15
avanitrachhadiya2155
saurabh1990aror
samim2000
number-digits
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
Program for factorial of a number