Given a positive number n. We need to find a number x such that sum of digits of x to itself is equal to n.
If no such x is possible print -1.
Input : n = 21 Output : x = 15 Explanation : x + its digit sum = 15 + 1 + 5 = 21 Input : n = 5 Output : -1
We iterate from 1 to n and for each intermediate number x find its digit sum and then add that to x, if that is equal to n then x will be our required answer.
// iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; return -1;
x = 35
This article is contributed by Shivam Pradhan (anuj_charm). 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find a Number X whose sum with its digits is equal to N
- 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
- Find smallest number with given number of digits and sum of digits
- Find the Largest 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 the smallest number whose digits multiply to a given number n
- Find count of digits in a number that divide the number
- Find maximum number that can be formed using digits of a given number
- Given a number n, find the first k digits of n^n