Smallest number with given sum of digits and sum of square of digits

Given sum of digits a and sum of square of digits b. Find the smallest number with given sum of digits and sum of the square of digits. The number should not contain more than 100 digits. Print -1 if no such number exists or if the number of digits is more than 100.

Examples:

Input : a = 18, b = 162
Output : 99
Explanation : 99 is the smallest possible number whose sum of digits = 9 + 9 = 18 and sum of squares of digits is 92+92 = 162.

Input : a = 12, b = 9
Output : -1



Approach:
Since the smallest number can be of 100 digits, it cannot be stored. Hence the first step to solve it will be to find the minimum number of digits which can give us the sum of digits as a and sum of the square of digits as b. To find the minimum number of digits, we can use Dynamic Programming. DP[a][b] signifies the minimum number of digits in a number whose sum of the digits will be a and sum of the square of digits will be b. If there does not exist any such number then DP[a][b] will be -1.

Since the number cannot exceed 100 digits, DP array will be of size 101*8101. Iterate for every digit, and try all possible combination of digits which gives us the sum of digits as a and sum of the square of digits as b. Store the minimum number of digits in DP[a][b] using the below recurrence relation:

DP[a][b] = min( minimumNumberOfDigits(a – i, b – (i * i)) + 1 )
where 1<=i<=9

After getting the minimum number of digits, find the digits. To find the digits, check for all combinations and print those digits which satisfies the condition below:

1 + dp[a – i][b – i * i] == dp[a][b]
where 1<=i<=9

If the condition above is met by any of i, reduce a by i and b by i*i and break. Keep on repeating the above process to find all the digits till a is 0 and b is 0.

Below is the C++ implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find the Smallest number 
// with given sum of digits and
// sum of square of digits
#include <bits/stdc++.h>
using namespace std;
  
int dp[901][8101];
  
// Top down dp to find minimum number of digits with
// given sum of dits a and sum of square of digits as b
int minimumNumberOfDigits(int a, int b)
{
    // Invalid condition 
    if (a > b || a < 0 || b < 0 || a > 900 || b > 8100)
        return -1;
      
    // Number of digits satisfied
    if (a == 0 && b == 0)
        return 0;
      
    // Memoization
    if (dp[a][b] != -1)
        return dp[a][b];
      
    // Intialize ans as maximum as we have to find the  
    // minimum number of digits 
    int ans = 101; 
      
    // Check for all possible combinations of digits
    for (int i = 9; i >= 1; i--) {
          
        // recurrence call 
        int k = minimumNumberOfDigits(a - i, b - (i * i)); 
          
        // If the combination of digits cannot give sum as a 
        // and sum of square of digits as b 
        if (k != -1)
            ans = min(ans, k + 1);
    }
      
    // Returns the minimum number of digits
    return dp[a][b] = ans;
}
  
// Function to print the digits that gives 
// sum as a and sum of square of digits as b
void printSmallestNumber(int a,int b)
{
      
    // initialize the dp array as -1
    memset(dp, -1, sizeof(dp));
      
    // base condition 
    dp[0][0] = 0;
      
    // function call to get the minimum number of digits  
    int k = minimumNumberOfDigits(a, b); 
      
    // When there does not exists any number
    if (k == -1 || k > 100)
        cout << "-1";
    else {
        // Printing the digits from the most significant digit
        while (a > 0 && b > 0) {
  
            // Trying all combinations 
            for (int i = 1; i <= 9; i++) {
                // checking conditions for minimum digits
                if (a >= i && b >= i * i && 
                    1 + dp[a - i][b - i * i] == dp[a][b]) {
                    cout << i;
                    a -= i;
                    b -= i * i;
                    break;
                }
            }
        }
    }
}
  
// Driver Code
int main()
{
    int a = 18, b = 162;
    // Function call to print the smallest number 
    printSmallestNumber(a,b); 
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the Smallest number
# with given sum of digits and
# sum of square of digits
  
dp=[[-1 for i in range(8101)]for i in range(901)]
  
# Top down dp to find minimum number of digits with
# given sum of dits a and sum of square of digits as b
def minimumNumberOfDigits(a,b):
    # Invalid condition 
    if (a > b or a < 0 or b < 0 or a > 900 or b > 8100):
        return -1
          
    # Number of digits satisfied
    if (a == 0 and b == 0):
        return 0
          
    # Memoization
    if (dp[a][b] != -1):
        return dp[a][b]
          
    # Intialize ans as maximum as we have to find the
    # minimum number of digits
    ans = 101
      
    #Check for all possible combinations of digits
    for i in range(9,0,-1):
          
        # recurrence call
        k = minimumNumberOfDigits(a - i, b - (i * i))
          
        # If the combination of digits cannot give sum as a
        # and sum of square of digits as b 
        if (k != -1):
            ans = min(ans, k + 1)
              
    # Returns the minimum number of digits
    dp[a][b] = ans
    return ans
  
# Function to print the digits that gives
# sum as a and sum of square of digits as b
def printSmallestNumber(a,b):
    # initialize the dp array as
    for i in range(901):
        for j in range(8101):
            dp[i][j]=-1
              
    # base condition
    dp[0][0] = 0
      
    # function call to get the minimum number of digits
    k = minimumNumberOfDigits(a, b)
      
    # When there does not exists any number
    if (k == -1 or k > 100):
        print(-1,end='')
    else:
        # Printing the digits from the most significant digit
          
        while (a > 0 and b > 0):
              
            # Trying all combinations
            for i in range(1,10):
                  
                #checking conditions for minimum digits
                if (a >= i and b >= i * i and
                    1 + dp[a - i][b - i * i] == dp[a][b]):
                    print(i,end='')
                    a -= i
                    b -= i * i
                    break
# Driver Code
if __name__=='__main__':
    a = 18
    b = 162
# Function call to print the smallest number
    printSmallestNumber(a,b)
      
# This code is contributed by sahilshelangia

chevron_right


Output:

99

Time Complexity : O(900*8100*9)
Auxiliary Space : O(900*8100)

Note: Time complexity is in terms of numbers as we are trying all possible combinations of digits.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : sahilshelangia