Given a string S consisting of a large hexadecimal number, the task is to check its divisibility by a given decimal number M. If divisible then print Yes else print No.
Input: S = “10”, M = 4
10 is 16 in decimal and (16 % 4) = 0
Input: S = “10”, M = 5
Approach: An approach used in this article will be used to avoid overflow. Iterate the entire string from the back-side.
If the remainder of the sub-string S[0…i] is known on division with M. Let’s call this remainder as R. This can be used to get the remainder when the substring S[0…i+1] is divided. To do that, first left shift the string S[0…i] by 1. This will be equivalent to multiplying the string by 16. Then, add S[i+1] to this and take its mod with M. With a little bit of modular arithmetic it boils down to
S[0…i+1] % M = (S[0…i] * 16 + S[i+1]) % M = ((S[0…i] % M * 16) + S[i+1]) % M
Thus, continue the above steps till the end of the string. If the final remainder is 0 then the string is divisible otherwise it is not.
Below is the implementation of the above approach:
- Check divisibility by 7
- Check if a large number is divisibility by 15
- To check divisibility of any large number by 999
- Check divisibility of binary string by 2^k
- Maximize profit when divisibility by two numbers have associated profits
- Find the count of natural Hexadecimal numbers of size N
- Sub-string Divisibility by 3 Queries
- Sub-string Divisibility by 11 Queries
- Divisibility by 12 for a large number
- Repeated Unit Divisibility
- Program for decimal to hexadecimal conversion
- Reverse bytes of a Hexadecimal Number
- Program to Convert Hexadecimal Number to Binary
- Convert a string to hexadecimal ASCII values
- Divisibility by 3 where each digit is the sum of all prefix digits modulo 10
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.