algorithmbinaryhardwaredivision

Algorithm in hardware to find out if number is divisible by five


I am trying to think of an algorithm to implement this for a given n bit binary number. I tried out many examples, but am unable to find out any pattern. So how shall I proceed?


Solution

  • How about this:

    Convert the number to base 4 (this is trivial by simply combining pairs of bits). 5 in base 4 is 11. The values base 4 that are divisible by 11 are somewhat familiar: 11, 22, 33, 110, 121, 132, 203, ...

    The rule for divisibility by 11 is that you add all the odd digits and all the even digits and subtract one from the other. If the result is divisible by 11 (which remember is 5), then it's divisible by 11 (which remember is 5).

    For example:

    123456d = 1 1110 0010 0100 0000b = 132021000_4
    
    The even digits are 1 2 2 0 0 : sum = 5d
    The odd digits are   3 0 1 0  : sum = 4d
    
    Difference is 1, which is not divisble by 5
    

    Or another one:

    123455d = 1 1110 0010 0011 1111b = 132020333_4
    
    The even digits are 1 2 2 3 3 : sum = 11d
    The odd digits are   3 0 0 3  : sum = 6d
    
    Difference is 5, which is a 5 or a 0
    

    This should have a fairly efficient HW implementation because it's mostly bit-slicing, followed by N/2 adders, where N is the number of bits in the number you're interested in.

    Note that after adding the digits and subtracting, the maximum value is 3/4 * N, so if you have 16-bit numbers max, you can get at most 12 as a result, so you only need to check for 0, ±5 and ±10 explicitly. If you're using 32-bit numbers then you can get at most 24 as a result, so you need to also check if the result is ±15 or ±20.