Find the smallest number such that the sum of its digits is N and it is divisible by .
Input : N = 5 Output : 500000 500000 is the smallest number divisible by 10^5 and sum of digits as 5. Input : N = 20 Output : 29900000000000000000000
To make a number divisible by we need at least N zeros at the end of the number. To make the number smallest, we append exactly N zeros to the end of the number. Now, we need to ensure the sum of the digits is N. For this, we will try to make the length of the number as small as possible to get the answer. Thus we keep on inserting 9 into the number till the sum doesn’t exceed N. If we have any remainder left, then we keep it as the first digit (most significant one) so that the resulting number is minimized.
The approach works well for all subtasks but there are 2 corner cases:
1. The first is that the final number may not fit into the data types present in C++/Java. Since we only need to output the number, we can use strings to store the answer.
2. The only corner case where the answer is 0 is N = 0.
3. There are no cases where the answer doesn’t exist.
The number is : 500000
Time Complexity : O(N)
- Smallest number with given sum of digits and sum of square of digits
- Find smallest number with given number of digits and sum of digits
- Smallest number divisible by first n numbers
- Smallest K digit number divisible by X
- Smallest even digits number not less than N
- Smallest number divisible by n and has at-least k trailing zeros
- Smallest n digit number divisible by given three numbers
- Largest number with the given set of N digits that is divisible by 2, 3 and 5
- Find N digits number which is divisible by D
- Number of digits to be removed to make a number divisible by 3
- Smallest number with at least n digits in factorial
- Possible to make a divisible by 3 number using all digits in an array
- Check whether sum of digits at odd places of a number is divisible by K
- Find the smallest number whose digits multiply to a given number n
- Smallest number k such that the product of digits of k is equal to 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 email@example.com. 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.
Improved By : jit_t