Check if a number is divisible by 3

后端 未结 16 2821
予麋鹿
予麋鹿 2020-12-01 01:30

I need to find whether a number is divisible by 3 without using %, / or *. The hint given was to use atoi() function. Any

相关标签:
16条回答
  • 2020-12-01 01:51

    Subtract 3 until you either

    a) hit 0 - number was divisible by 3

    b) get a number less than 0 - number wasn't divisible

    -- edited version to fix noted problems

    while n > 0:
        n -= 3
    while n < 0:
        n += 3
    return n == 0
    
    0 讨论(0)
  • 2020-12-01 01:54

    Split the number into digits. Add the digits together. Repeat until you have only one digit left. If that digit is 3, 6, or 9, the number is divisible by 3. (And don't forget to handle 0 as a special case).

    0 讨论(0)
  • 2020-12-01 01:57

    The current answers all focus on decimal digits, when applying the "add all digits and see if that divides by 3". That trick actually works in hex as well; e.g. 0x12 can be divided by 3 because 0x1 + 0x2 = 0x3. And "converting" to hex is a lot easier than converting to decimal.

    Pseudo-code:

    int reduce(int i) {
      if (i > 0x10)
        return reduce((i >> 4) + (i & 0x0F)); // Reduces 0x102 to 0x12 to 0x3.
      else
       return i; // Done.
    }
    bool isDiv3(int i) {
      i = reduce(i);
      return i==0 || i==3 || i==6 || i==9 || i==0xC || i == 0xF;
    }
    

    [edit] Inspired by R, a faster version (O log log N):

    int reduce(unsigned i) {
      if (i >= 6)
        return reduce((i >> 2) + (i & 0x03));
      else
       return i; // Done.
    }
    bool isDiv3(unsigned  i) {
      // Do a few big shifts first before recursing.
      i = (i >> 16) + (i & 0xFFFF);
      i = (i >> 8) + (i & 0xFF);
      i = (i >> 4) + (i & 0xF);
      // Because of additive overflow, it's possible that i > 0x10 here. No big deal.
      i = reduce(i);
      return i==0 || i==3;
    }
    
    0 讨论(0)
  • 2020-12-01 01:57
    inline bool divisible3(uint32_t x)  //inline is not a must, because latest compilers always optimize it as inline.
    {
        //1431655765 = (2^32 - 1) / 3
        //2863311531 = (2^32) - 1431655765
        return x * 2863311531u <= 1431655765u;
    }
    

    On some compilers this is even faster then regular way: x % 3. Read more here.

    0 讨论(0)
  • 2020-12-01 01:58

    A number is divisible by 3 if all the digits in the number when added gives a result 3, 6 or 9. For example 3693 is divisible by 3 as 3+6+9+3 = 21 and 2+1=3 and 3 is divisible by 3.

    0 讨论(0)
  • 2020-12-01 01:59

    You didn't tag this C, but since you mentioned atoi, I'm going to give a C solution:

    int isdiv3(int x)
    {
        div_t d = div(x, 3);
        return !d.rem;
    }
    
    0 讨论(0)
提交回复
热议问题