Is there any way to write “mod 31” without modulus/division operators?

后端 未结 5 1002
我在风中等你
我在风中等你 2020-12-03 16:02

Getting the modulus of a number can be easily done without the modulus operator or divisions, if your operand is a power of 2. In that case, the following formula holds:

5条回答
  •  抹茶落季
    2020-12-03 16:06

    int mod31(int a){
        while(a >= 31) {
            a -= 31;
        }
        return a;
    };
    

    It works if a > 0, but I doubt it will be faster than % operator.

提交回复
热议问题