Given number of digits n, print all n-digit numbers whose sum of digits adds upto given sum. Solution should not consider leading 0’s as digits.
Input: N = 2, Sum = 3 Output: 12 21 30 Input: N = 3, Sum = 6 Output: 105 114 123 132 141 150 204 213 222 231 240 303 312 321 330 402 411 420 501 510 600 Input: N = 4, Sum = 3 Output: 1002 1011 1020 1101 1110 1200 2001 2010 2100 3000
A simple solution would be to generate all N-digit numbers and print numbers that have sum of their digits equal to given sum. The complexity of this solution would be exponential.
A better solution is to generate only those N-digit numbers that satisfy the given constraints. The idea is to use recursion. We basically fill all digits from 0 to 9 into current position and maintain sum of digits so far. We then recurse for remaining sum and number of digits left. We handle leading 0’s separately as they are not counted as digits.
Below is a simple recursive implementation of above idea –
12 21 30
This article is contributed by Aditya Goel. 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.
- Count of n digit numbers whose sum of digits equals to given sum
- Print numbers with digits 0 and 1 only such that their sum is N
- Print all numbers less than N with at-most 2 unique digits
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1
- Print prime numbers with prime sum of digits in an array
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Count numbers in given range such that sum of even digits is greater than sum of odd digits
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Count numbers whose maximum sum of distinct digit-sum is less than or equals M
- Print all possible words from phone digits
- Print last k digits of a^b (a raised to power b)
- Print first k digits of 1/n where n is a positive integer
- Print individual digits as words without using if or switch
- Print a number containing K digits with digital root D