Built-in mod ('%') vs custom mod function: improve the performance of modulus operation

前端 未结 5 1703
逝去的感伤
逝去的感伤 2020-12-09 06:43

Recently I came to know that the mod(\'%\') operator is very slow. So I made a function which will work just like a%b. But is it faster than the mod operator?

Here\'

5条回答
  •  生来不讨喜
    2020-12-09 07:02

    Just contributing a little bit with this discussion. If you want to handle negative numbers, use the following function:

    inline long long mod(const long long x, const long long y) {
        if (x >= y) {
            return x % y;
        } else if (x < 0) {
            return (x % y + y) % y;
        } else {
            return x;
        }
    }
    

提交回复
热议问题