Divisiblity of 5 without using % and / operator

后端 未结 9 2303
隐瞒了意图╮
隐瞒了意图╮ 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 
    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.

提交回复
热议问题