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

后端 未结 5 1004
我在风中等你
我在风中等你 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条回答
  •  Happy的楠姐
    2020-12-03 16:23

    You could use successive addition / subtraction. There is no other trick since 31 is a prime number to see what the modulus of a number N is mod 31 you will have to divide and find the remainder.

    int mode(int number, int modulus) {
        int result = number;
    
        if (number >= 0) {
             while(result > modulus) { result = result - modulus;}
        } else {
             while (result < 0) { result = result + modulus;)
        }
    }
    

提交回复
热议问题