Given a very large number num (1 <= num <= 10^1000), print the number of digits that needs to be removed to make the number exactly divisible by 3. If it is not possible then print -1.
Input: num = "1234" Output: 1 Explanation: we need to remove one digit that is 1 or 4, to make the number divisible by 3.on Input: num = "11" Output: -1 Explanation: It is not possible to remove any digits and make it divisible by 3.
The idea is based on the fact that a number is multiple of 3 if and only if sum of its digits is multiple of 3 (See this for details).
One important observation used here is that the answer is at-most 2 if answer exists. So here are the only options for the function:
- Sum of digits is already equal to 0 modulo 3. Thus we don’t have to erase any digits.
- There exists such a digit that equals sum modulo 3. Then we just have to erase a single digits
- All of the digits are neither divisible by 3, nor equal to sum modulo 3. So two of such digits will sum up to number, which equals sum modulo 3, (2+2) mod 3=1, (1+1) mod 3=2.
Time Complexity: O(n) where n is the length of the number.
This article is contributed by Striver. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print digit's position to be removed to make a number divisible by 6
- Possible to make a divisible by 3 number using all digits in an array
- Minimum number of elements to be removed to make XOR maximum
- Minimum number of elements that should be removed to make the array good
- Find the minimum number of elements that should be removed to make an array good
- 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
- Check if the sum of digits of number is divisible by all of its digits
- Minimum number of given moves required to make N divisible by 25
- Find N digits number which is divisible by D
- Smallest number with sum of digits as N and divisible by 10^N
- Largest number with the given set of N digits that is divisible by 2, 3 and 5
- Minimum number to be added to all digits of X to make X > Y
- Program to check if a number is divisible by any of its digits
- Program to check if a number is divisible by sum of its digits