Divisiblity of 5 without using % and / operator

后端 未结 9 2263
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 02:14

how to check whether a number is divisible by 5 or not without using % and / operator. I want a quickest algorithm for this problem.

相关标签:
9条回答
  • 2020-12-02 02:56

    It finally got unlocked, so I can explain my comment, which incidentally turns out to generate better code than GCC does for x % 5 == 0. See here, fill in

    #include <stdint.h>
    bool divisible_by_5(uint32_t x)
    {
       return x % 5 == 0;
    }
    bool divisible_by_5_fast(uint32_t x)
    {
       return x * 0xCCCCCCCD <= 0x33333333;
    }
    

    I'll assume unsigned input, because the OP suggested an algorithm that only works with positive input. This method can be extended to signed input, but it's a little messy.

    0xCCCCCCCD is the modular multiplicative inverse of 5, modulo 232. Multiplying a multiple of k (for example, n * k) by the (modular) multiplicative inverse is equivalent to dividing by k, because

    (n * k) * inv(k) =
    // use associativity
    n * (k * inv(k)) =
    // use definition of multiplicative inverse
    n * 1 =
    // multiplicative identity
    n
    

    Modulo powers of two, a number has a modular multiplicative inverse iff it is odd.

    Since multiplying by an odd number is invertible and is actually a bijection, it can't map any non-multiples of k to the 0 - (232-1)/k range.

    So when it's outside that range, it can't have been a multiple of k.

    0x33333333 is (232-1)/5, so if x * 0xCCCCCCCD higher, x can't have been a multiple of 5.

    0 讨论(0)
  • 2020-12-02 03:03
    bool trythis(int number){
      Int start = number;
      Do{
        start = start - 5;
      } while (start > 5)
    
      If (start == 5 || start == 0) {
        Return true;
      } else return false;
    }
    
    0 讨论(0)
  • 2020-12-02 03:04

    A good starting point is to look into how division can be accomplished with multiplication and bit-shifts. This question is one place to look.

    In particular, you can follow the attached post to hit upon the following strategy. First, "divide by 5" using multiplication and bit-shifts:

     int32_t div5(int32_t dividend) {
         int64_t invDivisor = 0x33333333;
         return 1 + (int32_t) ((invDivisor * dividend) >> 32);
     }
    

    Then, take the result and multiply by 5:

    int result = div5(dividend) * 5;
    

    Then, result == dividend if and only dividend is divisible by 5.

    if(result == dividend) {
        // dividend is divisible by 5
    }
    else {
        // dividend is not divisible by 5
    }
    
    0 讨论(0)
提交回复
热议问题