对于unsigned int x,是否可以仅使用以下运算符(加上没有循环,分支或函数调用)来计算x%255(或一般2 ^ n - 1)?
!
,~
,&
,^
,|
,+
,<<
,>>
答案 0 :(得分:10)
是的,这是可能的。对于255,可以按如下方式完成:
unsigned int x = 4023156861;
x = (x & 255) + (x >> 8);
x = (x & 255) + (x >> 8);
x = (x & 255) + (x >> 8);
x = (x & 255) + (x >> 8);
// At this point, x will be in the range: 0 <= x < 256.
// If the answer 0, x could potentially be 255 which is not fully reduced.
// Here's an ugly way of implementing: if (x == 255) x -= 255;
// (See comments for a simpler version by Paul R.)
unsigned int t = (x + 1) >> 8;
t = !t + 0xffffffff;
t &= 255;
x += ~t + 1;
// x = 186
如果unsigned int
是32位整数,这将有效。
编辑:该模式应该足够明显,以便了解如何将其推广到2^n - 1
。您只需要弄清楚需要多少次迭代。对于n = 8
和32位整数,4次迭代就足够了。
编辑2:
这是一个稍微优化的版本,结合了Paul R.的条件减法代码:
unsigned int x = 4023156861;
x = (x & 65535) + (x >> 16); // Reduce to 17 bits
x = (x & 255) + (x >> 8); // Reduce to 9 bits
x = (x & 255) + (x >> 8); // Reduce to 8 bits
x = (x + ((x + 1) >> 8)) & 255; // Reduce to < 255
答案 1 :(得分:0)
只需创建一个包含所有值的数组(只需要32或64个条目(即128或512字节)。然后只需查看。
答案 2 :(得分:-1)
不确定。只需拿出一本旧的计算机体系结构教科书,然后在布尔代数上刷新内存。 CPU的ALU使用AND和OR执行此操作;你也可以。
但为什么?
学术练习?家庭作业?好奇?