Skip to content
Related Articles
Open in App
Not now

Related Articles

Check the divisibility of Hexadecimal numbers

Improve Article
Save Article
Like Article
  • Last Updated : 17 Jul, 2022
Improve Article
Save Article
Like Article

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.
Examples: 
 

Input: S = “10”, M = 4 
Output: Yes 
10 is 16 in decimal and (16 % 4) = 0
Input: S = “10”, M = 5 
Output: No 
 

 

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: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
const string CHARS = "0123456789ABCDEF";
const int DIGITS = 16;
 
// Function that returns true
// if s is divisible by m
bool isDivisible(string s, int m)
{
    // Map to map characters to real values
    unordered_map<char, int> mp;
 
    for (int i = 0; i < DIGITS; i++) {
        mp[CHARS[i]] = i;
    }
 
    // To store the remainder at any stage
    int r = 0;
 
    // Find the remainder
    for (int i = 0; i < s.size(); i++) {
        r = (r * 16 + mp[s[i]]) % m;
    }
 
    // Check the value of remainder
    if (!r)
        return true;
    return false;
}
 
// Driver code
int main()
{
    string s = "10";
    int m = 3;
 
    if (isDivisible(s, m))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
static char []CHARS = "0123456789ABCDEF".toCharArray();
static int DIGITS = 16;
 
// Function that returns true
// if s is divisible by m
static boolean isDivisible(String s, int m)
{
    // Map to map characters to real values
    Map<Character, Integer> mp = new HashMap<>();
 
    for (int i = 0; i < DIGITS; i++)
    {        
        mp. put(CHARS[i], i);
    }
 
    // To store the remainder at any stage
    int r = 0;
 
    // Find the remainder
    for (int i = 0; i < s.length(); i++)
    {
        r = (r * 16 + mp.get(s.charAt(i))) % m;
    }
 
    // Check the value of remainder
    if (r == 0)
        return true;
    return false;
}
 
// Driver code
public static void main(String []args)
{
    String s = "10";
    int m = 3;
 
    if (isDivisible(s, m))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of the approach
CHARS = "0123456789ABCDEF";
DIGITS = 16;
 
# Function that returns true
# if s is divisible by m
def isDivisible(s, m) :
 
    # Map to map characters to real value
    mp = dict.fromkeys(CHARS, 0);
 
    for i in range( DIGITS) :
        mp[CHARS[i]] = i;
 
    # To store the remainder at any stage
    r = 0;
 
    # Find the remainder
    for i in range(len(s)) :
        r = (r * 16 + mp[s[i]]) % m;
 
    # Check the value of remainder
    if (not r) :
        return True;
         
    return False;
 
# Driver code
if __name__ == "__main__" :
     
    s = "10";
    m = 3;
 
    if (isDivisible(s, m)) :
        print("Yes");
    else :
        print("No");
 
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
static char []CHARS = "0123456789ABCDEF".ToCharArray();
static int DIGITS = 16;
 
// Function that returns true
// if s is divisible by m
static bool isDivisible(String s, int m)
{
    // Map to map characters to real values
    Dictionary<char, int> mp = new Dictionary<char, int>();
 
    for (int i = 0; i < DIGITS; i++)
    {        
        if(mp.ContainsKey(CHARS[i]))
            mp[CHARS[i]] = i;
        else
            mp.Add(CHARS[i], i);
    }
 
    // To store the remainder at any stage
    int r = 0;
 
    // Find the remainder
    for (int i = 0; i < s.Length; i++)
    {
        r = (r * 16 + mp[s[i]]) % m;
    }
 
    // Check the value of remainder
    if (r == 0)
        return true;
    return false;
}
 
// Driver code
public static void Main(String []args)
{
    String s = "10";
    int m = 3;
 
    if (isDivisible(s, m))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript implementation of the approach
 
var CHARS = "0123456789ABCDEF";
var DIGITS = 16;
 
// Function that returns true
// if s is divisible by m
function isDivisible(s, m)
{
    // Map to map characters to real values
    var mp = new Map();
 
    for (var i = 0; i < DIGITS; i++) {
        mp.set(CHARS[i], i);
    }
 
    // To store the remainder at any stage
    var r = 0;
 
    // Find the remainder
    for (var i = 0; i < s.length; i++) {
        r = (r * 16 + mp.get(s[i])) % m;
    }
 
    // Check the value of remainder
    if (!r)
        return true;
    return false;
}
 
// Driver code
var s = "10";
var m = 3;
if (isDivisible(s, m))
    document.write( "Yes");
else
    document.write( "No");
 
</script>


Time complexity: O(n)

Auxiliary Space: O(logn)


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!