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)
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- 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 K digit number divisible by X
- Smallest number divisible by first n numbers
- Smallest even digits number not less than N
- Smallest odd number with N digits
- Smallest Even number with N digits
- Smallest odd digits number not less than N
- C++ Program for Smallest K digit number divisible by X
- Smallest number divisible by n and has at-least k trailing zeros
- Smallest n digit number divisible by given three numbers
- Length of the smallest number which is divisible by K and formed by using 1's only
- Smallest number greater than or equal to N divisible by K
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