问题描述
对于特定的基数,是否可以创建比标准%运算符更快的整数模数?
对于我的程序,我需要大约1000-4000(例如n%2048).有没有比简单地执行n模数2048更快的方法?n%2048
?
如果在编译时知道分母为2的幂,例如2048,则可以减去1并进行按位与运算. /p>
也就是说:
n % m == n & (m - 1)
...其中m
是2的幂.
例如:
22 % 8 == 22 - 16 == 6
Dec Bin
----- -----
22 = 10110
8 = 01000
8 - 1 = 00111
22 & (8 - 1) = 10110
& 00111
-------
6 = 00110
请记住,一个好的编译器将对%
进行自己的优化,甚至可能与上述技术一样快.算术运算符往往会进行大量优化.
Is there a trick for creating a faster integer modulus than the standard % operator for particular bases?
For my program, I'd be looking for around 1000-4000 (e.g. n%2048). Is there a quicker way to perform n modulus 2048 than simply: n%2048
?
If the denominator is known at compile time to be a power of 2, like your example of 2048, you could subtract 1 and do a bitwise-and.
That is:
n % m == n & (m - 1)
...where m
is a power of 2.
For example:
22 % 8 == 22 - 16 == 6
Dec Bin
----- -----
22 = 10110
8 = 01000
8 - 1 = 00111
22 & (8 - 1) = 10110
& 00111
-------
6 = 00110
Bear in mind that a good compiler will have its own optimizations for %
, maybe even enough to be as fast as the above technique. Arithmetic operators tend to be pretty heavily optimized.
这篇关于C/C#中的模数更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!