Integer division without using the / or * operator

后端 未结 7 477
梦如初夏
梦如初夏 2021-01-14 15:34

I am going through an algorithms and datastructures textbook and came accross this question:

1-28. Write a function to perform integer division withou

7条回答
  •  逝去的感伤
    2021-01-14 16:14

    The simplest way to perform a division is by successive subtractions: subtract b from a as long as a remains positive. The quotient is the number of subtractions performed.

    This can be pretty slow, as you will perform q subtractions and tests.

    With a=28 and b=3,

    28-3-3-3-3-3-3-3-3-3=1
    

    the quotient is 9 and the remainder 1.

    The next idea that comes to mind is to subtract several times b in a single go. We can try with 2b or 4b or 8b... as these numbers are easy to compute with additions. We can go as for as possible as long as the multiple of b does not exceed a.

    In the example, 2³.3 is the largest multiple which is possible

    28>=2³.3
    

    So we subtract 8 times 3 in a single go, getting

    28-2³.3=4
    

    Now we continue to reduce the remainder with the lower multiples, , 2 and 1, when possible

    4-2².3<0
    4-2.3 <0
    4-1.3 =1
    

    Then our quotient is 2³+1=9 and the remainder 1.

    As you can check, every multiple of b is tried once only, and the total number of attempts equals the number of doublings required to reach a. This number is just the number of bits required to write q, which is much smaller than q itself.

提交回复
热议问题