按位与到位模运算符运算符

2023-09-10 22:44:57 作者:花开淡墨

我们知道,两个功率的例子模可以pssed这样EX $ P $:

We know that for example modulo of power of two can be expressed like this:

  x % 2 inpower n == x & (2 inpower n - 1).

例如:

x % 2 == x & 1
x % 4 == x & 3
x % 8 == x & 7 

那么两个数字的一​​般非电力?

What about general nonpower of two numbers?

让我们说:

X%7 ==?

推荐答案

首先,它实际上是不准确的说,

First of all, it's actually not accurate to say that

x % 2 == x & 1

简单的反例: X = -1 。在许多语言,包括Java, 1%2 == -1 。也就是说,不一定模的传统的数学定义。 Java调用它的余运算符为例。

Simple counterexample: x = -1. In many languages, including Java, -1 % 2 == -1. That is, % is not necessarily the traditional mathematical definition of modulo. Java calls it the "remainder operator", for example.

至于按位优化,只能模两可轻松在按位算术做的权力。一般来说,基础的的B仅模权力的可以轻松地与基地的乙做的数字再presentation。

With regards to bitwise optimization, only modulo powers of two can "easily" be done in bitwise arithmetics. Generally speaking, only modulo powers of base b can "easily" be done with base b representation of numbers.

在基地10,例如,对于非负 N N模10 ^氏/ code>只是走最低显著 K 的数字。

In base 10, for example, for non-negative N, N mod 10^k is just taking the least significant k digits.

JLS余15.17.3操作员% 维基/模操作 JLS 15.17.3 Remainder Operator % Wikipedia/Modulo Operation