UVA 128 - Software CRC

2014-11-24 10:20:23 · 作者: · 浏览: 0

给出一串字符串,求其循环冗余校验码.

求法:把整个字符串看成一个整数m,第一个字符作为这个整数的最高字节,第二个字符作为次高字节,etc...

要求在这个整数最后加上两个字节变成m2,使其整除34943.

解法:快速幂取模,粒度为一个字节.

#include 
  
   
#include 
   
     using namespace std; #define MOD 34943 char message[1025]; int mod_pow(int a, int b, int c){ int res = 1, t = a; while(b){ if(b & 1)res = res * t % c; t = t * t % c; b >>= 1; } return res % c; } int main(){ while(gets(message)){ if(message[0] == '#' && message[1] == 0)break; int ans = 0, len = strlen(message), shift = 2; for(int i = len - 1; i >= 0; --i){ ans = (ans + message[i] * mod_pow(256, shift, MOD) % MOD) % MOD; shift++; } ans = (MOD - ans) % MOD; printf("%02X %02X\n", ans >> 8, ans & ((1 << 8) - 1)); } return 0; }