Find smallest number with given number of digits and sum of digits

25 May, 2022
How to find the smallest number with given digit sum s and number of digits d? Examples :  
Input  : s = 9, d = 2
Output : 18
There are many other possible numbers 
like 45, 54, 90, etc with sum of digits
as 9 and number of digits as 2. The 
smallest of them is 18.

Input  : s = 20, d = 3
Output : 299
 
A Simple Solution is to consider all m digit numbers and keep track of minimum number with digit sum as s. A close upper bound on time complexity of this solution is O(10m).There is a Greedy approach to solve the problem. The idea is to one by one fill all digits from rightmost to leftmost (or from least significant digit to most significant). We initially deduct 1 from sum s so that we have smallest digit at the end. After deducting 1, we apply greedy approach. We compare remaining sum with 9, if remaining sum is more than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits from right to left, we put the highest digits on the right side. Below is implementation of the idea. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the smallest number that can be// formed from given sum of digits and number of digits.#include <iostream>using namespace std; // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.void findSmallest(int m, int s){    // If sum of digits is 0, then a number is possible    // only if number of digits is 1.    if (s == 0)    {        (m == 1)? cout << "Smallest number is " << 0                : cout << "Not possible";        return ;    }     // Sum greater than the maximum possible sum.    if (s > 9*m)    {        cout << "Not possible";        return ;    }     // Create an array to store digits of result    int res[m];     // deduct sum by one to account for cases later    // (There must be 1 left for the most significant    //  digit)    s -= 1;     // Fill last m-1 digits (from right to left)    for (int i=m-1; i>0; i--)    {        // If sum is still greater than 9,        // digit must be 9.        if (s > 9)        {            res[i] = 9;            s -= 9;        }        else        {            res[i] = s;            s = 0;        }    }     // Whatever is left should be the most significant    // digit.    res[0] = s + 1;  // The initially subtracted 1 is                     // incorporated here.     cout << "Smallest number is ";    for (int i=0; i<m; i++)        cout << res[i];} // Driver codeint main(){    int s = 9, m = 2;    findSmallest(m, s);    return 0;}
// Java program to find the smallest number that can be// formed from given sum of digits and number of digits class GFG{    // Function to print the smallest possible number with digit sum 's'    // and 'm' number of digits    static void findSmallest(int m, int s)    {        // If sum of digits is 0, then a number is possible        // only if number of digits is 1        if (s == 0)        {            System.out.print(m == 1 ? "Smallest number is 0" : "Not possible");                         return ;        }          // Sum greater than the maximum possible sum        if (s > 9*m)        {            System.out.println("Not possible");            return ;        }          // Create an array to store digits of result        int[] res = new int[m];          // deduct sum by one to account for cases later        // (There must be 1 left for the most significant        //  digit)        s -= 1;          // Fill last m-1 digits (from right to left)        for (int i=m-1; i>0; i--)        {            // If sum is still greater than 9,            // digit must be 9            if (s > 9)            {                res[i] = 9;                s -= 9;            }            else            {                res[i] = s;                s = 0;            }        }          // Whatever is left should be the most significant        // digit        res[0] = s + 1;  // The initially subtracted 1 is                        // incorporated here          System.out.print("Smallest number is ");        for (int i=0; i<m; i++)            System.out.print(res[i]);    }         // driver program    public static void main (String[] args)    {        int s = 9, m = 2;        findSmallest(m, s);    }} // Contributed by Pramod Kumar
# Prints the smallest possible# number with digit sum 's'# and 'm' number of digits. def findSmallest(m,s):     # If sum of digits is 0,    # then a number is possible    # only if number of digits is 1.    if (s == 0):                 if(m == 1) :              print("Smallest number is 0")        else :              print("Not possible")        return      # Sum greater than the    # maximum possible sum.    if (s > 9*m):             print("Not possible")        return      # Create an array to    # store digits of result    res=[0 for i in range(m+1)]      # deduct sum by one to    # account for cases later    # (There must be 1 left    # for the most significant    #  digit)    s -= 1      # Fill last m-1 digits    # (from right to left)    for i in range(m-1,0,-1):             # If sum is still greater than 9,        # digit must be 9.        if (s > 9):                     res[i] = 9            s -= 9             else:                     res[i] = s            s = 0      # Whatever is left should    # be the most significant    # digit.    # The initially subtracted 1 is    # incorporated here.    res[0] = s + 1                          print("Smallest number is ",end="")    for i in range(m):        print(res[i],end="")  s = 9m = 2findSmallest(m, s) # This code is contributed# by Anant Agarwal.
// C# program to find the smallest// number that can be formed from// given sum of digits and number// of digitsusing System; class GFG{    // Function to print the smallest    // possible number with digit sum 's'    // and 'm' number of digits    static void findSmallest(int m, int s)    {        // If sum of digits is 0,        // then a number is possible        // only if number of digits is 1        if (s == 0)        {            Console.Write(m == 1 ?                          "Smallest number is 0" :                                  "Not possible");                         return ;        }         // Sum greater than the        // maximum possible sum        if (s > 9 * m)        {            Console.Write("Not possible");            return ;        }         // Create an array to        // store digits of result        int []res = new int[m];         // deduct sum by one to account        // for cases later (There must be        // 1 left for the most significant        // digit)        s -= 1;         // Fill last m-1 digits        // (from right to left)        for (int i = m - 1; i > 0; i--)        {            // If sum is still greater            // than 9, digit must be 9            if (s > 9)            {                res[i] = 9;                s -= 9;            }            else            {                res[i] = s;                s = 0;            }        }         // Whatever is left should be        // the most significant digit                 // The initially subtracted 1 is        // incorporated here        res[0] = s + 1;         Console.Write("Smallest number is ");        for (int i = 0; i < m; i++)            Console.Write(res[i]);    }         // Driver Code    public static void Main ()    {        int s = 9, m = 2;        findSmallest(m, s);    }} // This code is contributed by nitin mittal.
<?php// PHP program to find the smallest// number that can be formed from// given sum of digits and number// of digits. // Prints the smallest possible// number with digit sum 's'// and 'm' number of digits.function findSmallest($m, $s){    // If sum of digits is 0, then    // a number is possible only if    // number of digits is 1.    if ($s == 0)    {        if(($m == 1) == true)                 echo "Smallest number is " , 0;        else        echo "Not possible";        return ;    }     // Sum greater than the    // maximum possible sum.    if ($s > 9 * $m)    {        echo "Not possible";        return ;    }     // Create an array to store    // digits of result int res[m];    // deduct sum by one to account    // for cases later (There must    // be 1 left for the most    // significant digit)    $s -= 1;     // Fill last m-1 digits    // (from right to left)    for ($i = $m - 1; $i > 0; $i--)    {        // If sum is still greater        // than 9, digit must be 9.        if ($s > 9)        {            $res[$i] = 9;            $s -= 9;        }        else        {            $res[$i] = $s;            $s = 0;        }    }     // Whatever is left should be    // the most significant digit.         // The initially subtracted 1    // is incorporated here.    $res[0] = $s + 1;                           echo "Smallest number is ";    for ($i = 0; $i < $m; $i++)        echo $res[$i];} // Driver code$s = 9; $m = 2;findSmallest($m, $s); // This code is contributed by ajit?>
<script> // Javascript program to find the smallest number that can be// formed from given sum of digits and number of digits. // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.function findSmallest(m, s){    // If sum of digits is 0, then a number is possible    // only if number of digits is 1.    if (s == 0)    {        (m == 1)? document.write("Smallest number is ") + 0                : document.write("Not possible");        return ;    }     // Sum greater than the maximum possible sum.    if (s > 9*m)    {        document.write("Not possible");        return ;    }     // Create an array to store digits of result    let res = new Array(m);     // deduct sum by one to account for cases later    // (There must be 1 left for the most significant    // digit)    s -= 1;     // Fill last m-1 digits (from right to left)    for (let i=m-1; i>0; i--)    {        // If sum is still greater than 9,        // digit must be 9.        if (s > 9)        {            res[i] = 9;            s -= 9;        }        else        {            res[i] = s;            s = 0;        }    }     // Whatever is left should be the most significant    // digit.    res[0] = s + 1; // The initially subtracted 1 is                    // incorporated here.     document.write("Smallest number is ");    for (let i=0; i<m; i++)        document.write(res[i]);} // Driver code      let s = 9, m = 2;    findSmallest(m, s);     // This code is contributed by Mayank Tyagi </script>
Output :  
Smallest number is 18
Time Complexity: O(m), where m represents the value of given integer.
Auxiliary Space: O(m), where m represents the value of given integer.
We will soon be discussing approach to find the largest possible number with given sum of digits and number of digits.This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
jit_t
mayanktyagi1709
tamanna17122007
MAQ Software
number-digits
Greedy
MAQ Software
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.