Smallest N digit number whose sum of square of digits is a Perfect Square
Given an integer N, find the smallest N digit number such that the sum of the square of digits (in decimal representation) of the number is also a perfect square. If no such number exists, print -1.
Examples:
Input : N = 2
Output : 34
Explanation:
The smallest possible 2 digit number whose sum of square of digits is a perfect square is 34 because 32 + 42 = 52.
Input : N = 1
Output : 1
Explanation:
The smallest possible 1 digit number is 1 itself.
Method 1:
To solve the problem mentioned above we can use Backtracking. Since we want to find the minimum N digit number satisfying the given condition, the answer will have digits in non-decreasing order. Therefore we generate the possible numbers recursively keeping track of following in each recursive step :
- position: the current position of the recursive step i.e. which position digit is being placed.
- prev: the previous digit placed because the current digit has to be greater than equal to prev.
- sum: the sum of squares of digits placed till now. When digits are placed, this will be used to check whether the sum of squares of all digits placed is a perfect square or not.
- A vector which stores what all digits have been placed till this position.
If placing a digit at a position and moving to the next recursive step leads to a possible solution then return 1, else backtrack.
Below is the implementation of the above approach:
// CPP implementation to find Smallest N // digit number whose sum of square // of digits is a Perfect Square #include <bits/stdc++.h> using namespace std; // function to check if // number is a perfect square int isSquare(int n) { int k = sqrt(n); return (k * k == n); } // function to calculate the // smallest N digit number int calculate(int pos, int prev, int sum, vector<int>& v) { if (pos == v.size()) return isSquare(sum); // place digits greater than equal to prev for (int i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // check if palcing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v)) return 1; // else backtrack sum -= i * i; } return 0; } string minValue(int n) { vector<int> v(n); if (calculate(0, 1, 0, v)) { // create a string representing // the N digit number string answer = ""; for (int i = 0; i < v.size(); i++) answer += char(v[i] + '0'); return answer; } else return "-1"; } // driver code int main() { // initialise N int N = 2; cout << minValue(N); return 0; } |
34
Method 2:
The above-mentioned problem can also be solved using Dynamic Programming. If we observe the question carefully we see that it can be converted to the standard Coin Change problem. Given N as the number of digits, the base answer will be N 1’s, the sum of the square of whose digits will be N.
- If N itself is a perfect square then the N times 1 will be the final answer.
- Otherwise, we will have to replace some 1’s in the answer with other digits from 2-9. Each replacement in the digit will increase the sum of the square by a certain amount and since 1 can be changed to only 8 other possible digits there are only 8 such possible increments. For example, if 1 is changed to 2, then increment will be 22 – 12 = 3. Similarly, all possible changes are : {3, 8, 15, 24, 35, 48, 63, 80}.
So the problem now can be interpreted as having 8 kinds of coins of the aforementioned values and we can use any coin any number of times to create the required sum. The sum of squares will lie in the range of N (all digits are 1) to 81 * N (all digits are 9). We just have to consider perfect square sums in the range and use the idea of coin change to find the N digits that will be in the answer. One important point we need to take into account is that we have to find the smallest N digit number not the number with the smallest square sum of digits.
Below is the implementation of the above-mentioned approach:
// CPP implementation to find the Smallest // N digit number whose sum of square // of digits is a Perfect Square #include <bits/stdc++.h> using namespace std; long long value[8100006]; int first[8100006]; // array for all possible changes int coins[8] = { 3, 8, 15, 24, 35, 48, 63, 80 }; void coinChange() { const long long inf = INT_MAX; // iterating till 81 * N // since N is at max 10^5 for (int x = 1; x <= 8100005; x++) { value[x] = inf; for (auto c : coins) { if (x - c >= 0 && value[x - c] + 1 < value[x]) { value[x] = min(value[x], value[x - c] + 1); // least value of coin first[x] = c; } } } } // function to find the // minimum possible value string minValue(int n) { // aplying coin change for all the numbers coinChange(); string answer = ""; // check if number is // perfect square or not if ((sqrt(n) * sqrt(n)) == n) { for (int i = 0; i < n; i++) answer += "1"; return answer; } long long hi = 81 * n; long long lo = sqrt(n); // keeps a check whether // number is found or not bool found = false; long long upper = 81 * n; long long lower = n; // sotring suffix strings string suffix; bool suf_init = false; while ((lo * lo) <= hi) { lo++; long long curr = lo * lo; long long change = curr - n; if (value[change] <= lower) { // build a suffix string found = true; if (lower > value[change]) { // number to be used for updation of lower, // first values that will be used // to construct the final number later lower = value[change]; upper = change; suffix = ""; suf_init = true; int len = change; while (len > 0) { int k = sqrt(first[len] + 1); suffix = suffix + char(k + 48); len = len - first[len]; } } else if (lower == value[change]) { string tempsuf = ""; int len = change; while (len > 0) { int k = sqrt(first[len] + 1); tempsuf = tempsuf + char(k + 48); len = len - first[len]; } if (tempsuf < suffix or suf_init == false) { lower = value[change]; upper = change; suffix = tempsuf; suf_init = true; } } } } // check if number is found if (found) { // construct the number from first values long long x = lower; for (int i = 0; i < (n - x); i++) answer += "1"; long long temp = upper; // fill in rest of the digits while (temp > 0) { int dig = sqrt(first[temp] + 1); temp = temp - first[temp]; answer += char(dig + '0'); } return answer; } else return "-1"; } // driver code int main() { // initialise N int N = 2; cout << minValue(N); return 0; } |
34
Time Complexity : O(81 * N)
Recommended Posts:
- Largest N digit Octal number which is a Perfect square
- Check if a number is perfect square without finding square root
- Minimum digits to remove to make a number Perfect Square
- Smallest number with given sum of digits and sum of square of digits
- Largest number that is not a perfect square
- Check if given number is perfect square
- Find the Next perfect square greater than a given number
- Largest factor of a given number which is a perfect square
- Check whether the number can be made perfect square after adding 1
- Least number to be added to or subtracted from N to make it a Perfect Square
- Largest Divisor of a Number not divisible by a perfect square
- Check whether the number can be made perfect square after adding K
- Find minimum number to be divided to make a number a perfect square
- Smallest N digit number which is a perfect fourth power
- Number of times the largest perfect square number can be subtracted from N
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.

