How do computers find modulus?

北城余情 提交于 2019-12-19 02:15:24

问题


Is there some cool algorithm with bit wise operations?


回答1:


Often, the modulus and divide operations on a processor are the same thing. For instance, refer to http://jsimlo.sk/docs/cpu/index.php/div.html . This is the implementation of the divide instruction on Intel processors.




回答2:


Most of the time, modulus is just computed by dividing the two numbers. The quotient is stored in one register, and the remainder is stored in the other register. You would go after the remainder.




回答3:


If the divisor is known in advance (e.g. for code produced by a C compiler, this is a constant known at compile time) then integer division (from which the modulus can be easily obtained) can sometimes be implemented with a multiplication and a shift. See this article for details (warning: this is not light reading).

In many processors, integer multiplication is vastly faster than integer division; some processors do not even have an integer division opcode (multiplication on n-bit values can be optimized into a circuit of depth O(log n), whereas there is no known method to optimize a division circuit below a depth of O(n)).




回答4:


x mod y = x - y*(x/y)

where (x/y) is an integer divide.




回答5:


Apart from the obvious method using DIV and IDIV (for x86) as mentioned above, the result of any number modulo'd by a power of two can be calculated by taking the bitwise and: x mod y where y is pow2 is the same as x AND (y - 1). Most compilers perform this when possible, as division is far more expensive than bitwise ops




回答6:


Also checking the modulo 2 is easy, as it only need to check the least significant bit, usually.

Quoting wikipedia:

For special cases, on some hardware, faster alternatives exist. For example, the modulo of powers of 2 can alternatively be expressed as a bitwise AND operation:

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

Examples (assuming x is a positive integer):

x % 2 == x & 1

x % 4 == x & 3

x % 8 == x & 7

In devices and software that implement bitwise operations more efficiently than modulo, these alternative forms can result in faster calculations.



来源:https://stackoverflow.com/questions/5454574/how-do-computers-find-modulus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!