Given a positive number N. We need to find number(s) such that sum of digits of those numbers to themselves is equal to N. If no such number is possible print -1. Here N
Input : N = 21 Output : X = 15 Explanation : X + its digit sum = 15 + 1 + 5 = 21 Input : N = 5 Output : -1 Input : N = 100000001 Output : X = 99999937 X = 100000000
Method 1 : (Naive Approach)
We have already discussed the approach here. The approach might not work for N as large as .
Method 2 : (Efficient)
It is a fact that for a number X < = 1000000000, the sum of digits never exceeds 100. Using this piece of information, we can iterate over all possibilities in the range 0 to 100 on both the sides of the number and check if the number X is eqaul to N – sum of digits of X. All the possibilities will be covered in this range.
X = 100000000 X = 99999937
The maximum complexity of this approach can be where len is the number of digits in the number max(len) = 9. Thus the complexity can almost be said to be
- Find a number x such that sum of x and its digits is equal to given n.
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Find the first N integers such that the sum of their digits is equal to 10
- Sum of digits equal to a given number in PL/SQL
- Find maximum product of digits among numbers less than or equal to N
- Smallest number k such that the product of digits of k is equal to n
- Greatest number less than equal to B that can be formed from the digits of A
- Find the average of k digits from the beginning and l digits from the end of the given number
- Check if product of digits of a number at even and odd places is equal
- Largest number smaller than or equal to n and digits in non-decreasing order
- Count of numbers whose sum of increasing powers of digits is equal to the number itself
- Find the Largest number with given number of digits and sum of digits
- Find smallest number with given number of digits and sum of digits
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Find maximum number that can be formed using digits of a given number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.