移位实现模七和模十三的操作
模七和模十三其实都可以通过移位操作来实现。
先说模七。对任意数N,写成如下形式:
N = 8*x + y。其中x = N/8 = N>>3,y = N%8 = N & 0x7。
此时我们有N%7=(8*x+y)%7 = x+y。
可以对x+y进行同样的处理直到(x+y)%7<8,此时结果要么为0,要么为(x+y)%7。
对于模十三,方法是一样一样的。
N = 16*x + y。其中x = N/16 = N>>4,y = N%16 = N & 0xf。
此时有N%13 = (16*x+y)%13 = 3*x+y。
继续对(3*x+y)进行同样的处理,直到(3*x+y)%13小于16,此时结果要么为(3*x+y)%13,要么为(3*x+y)%13-13。
具体的代码实现如下:
#include
#include
//N=8x+y,x=N/8,y=N%8,N%7=(x+y)%7,do the same until (x+y)%7 is less than 8.
int mod7(int data)
{
int re = data & 0x7;
int quo = data >> 3;
int s = re + quo;
while(s > 7)
{
re = s & 0x7;
quo = s >> 3;
s = re + quo;
}
if(s < 7)
return s;
else
return 0;//s=7.
}
//N=16x+y,x=N/16,y=N%16,N%13=(3x+y)%13,do the same until (3x+y)%13 is less than 16.
int mod13(int data)
{
int re = data & 0xf;
int quo = data >> 4;
int s = 3*quo + re;
while(s > 15)
{
re = s & 0xf;
quo = s >> 4;
s = 3*quo + re;
}
if(s < 13)
return s;
else
return s-13;
}
int main()
{
for(int i=0;i<1000;i++)
{
int w = rand();
if(w%13 != mod13(w) || w%7 != mod7(w))
{
printf("w = %d ",w);
printf("w mod 7 and w mod 13 res are : %d %d %d %d
",mod7(w),mod13(w),w%7,w%13);
}
else
{
printf("You got the right answer!
");
}
}
return 0;
}
参考csdn:http://blog.csdn.net/tjltail/article/details/1482316
#算法 #编程学习