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
- Smallest number k such that the product of digits of k is equal to n
- 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 maximum number that can be formed using digits of a given number
- Find count of digits in a number that divide the number
- Find the smallest number whose digits multiply to a given number n
- Find first and last digits of a number
- Given a number n, find the first k digits of n^n
- Find M-th number whose repeated sum of digits of a number is N
- Find N digits number which is divisible by D
- Find the total Number of Digits in (N!)N
Improved By : vt_m