按位和代替模运算符 [英] Bitwise and in place of modulus operator

查看:38
本文介绍了按位和代替模运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,例如,2 的幂的模可以这样表示:

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 

两个数的一般非幂呢?

让我们说:

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.

关于按位优化,在按位算术中只能轻松"完成2的模幂.一般而言,只有以 b 为底的数的模幂才能轻松"完成以 b 为底的数字表示.

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 中,对于非负 NN mod 10^k 只是取最低有效的 k 位.

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

这篇关于按位和代替模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆