Logic to check the number is divisible by 3 or not?

后端 未结 10 1478
清歌不尽
清歌不尽 2021-01-14 16:31

without using %, / or * , I have to find the no. is divisible by 3 or not?

it might be an interview question.

Thanks.

10条回答
  •  死守一世寂寞
    2021-01-14 17:03

    To print a count sequence which is divisible by 3 without division or modulus operator.

    Notice the count sequence:

    00: 00(00)
    01: 0001
    02: 0010
    03: 00(11)
    04: 0100
    05: 0101
    06: 01(10)
    07: 0111
    08: 1000
    09: 10(01)
    10: 1010
    11: 1011
    12: 11(00)
    13: 1101
    14: 1110
    15: 11(11)
    16: 10000
    17: 10001
    18: 100(10)
    19: 10011
    20: 10100
    21: 101(01)
    

    Note that the last two bits of those numbers which are divisible by three (shown in brackets) are cycling through {00, 11, 10, 01} . What we need to check is if the last two bits of the count sequence has these bits in a sequence.

    First we start matching with mask = 00 and loop while the first number is not encountered with the lower two bits 00. When a match is found we then do (mask + 03) & 0x03 which gets us the next mask in the set. And we continue to match the last two bits of the next count with 11. Which can be done by ((count & 3) == mask)

    The code is

    #include 
    
    int main (void)
    {
      int i=0;
      unsigned int mask = 0x00;
    
      for (i=0; i<100;i++)
      {
        if ((i&0x03) == mask)
        {
          printf ("\n%d", i);
          mask = (mask + 3) & 0x03;
        }
      }
      printf ("\n");
      return 0;
    }
    

    This is not a general one. Best is to use the solution which @nightcracker have suggested

    Also if you really want to implement the division operation i without using the divide operations. I would tell you to have a look at the Non-Restoring Division Algorithm, this can be done in program with a lot of bit manipulations with bitwise operators. Here are some links and references for it.

    Wikipedia Link

    Here is a demo from UMass

    Also have a look at Computer Organization by Carl Hamacher, Zvonko Vranesic, Safwat Zaky

提交回复
热议问题