POJ 2635 The Embarrassed Cryptographer 大数模
题目: http://poj.org/problem?id=2635
利用同余模定理大数拆分取模,但是耗时,需要转化为高进制,这样位数少,循环少,这里转化为1000进制的,如果转化为10000进制,需要long long
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <cmath> 5 using namespace std; 6 7 int p[78600]; 8 bool prime[1001001]; 9 void prime_init() 10 { 11 memset(prime, 1, sizeof(prime)); 12 prime[1] = 0; 13 for(int i = 4; i <= 1001000; i += 2) 14 prime[i] = 0; 15 for(int i = 3; i <= sqrt(1001000); i += 2) 16 { 17 if(prime[i]) 18 { 19 for(int j = i*i; j <= 1001000; j += i+i) 20 prime[j] = 0; 21 } 22 } 23 int cnt = 0; 24 for(int i = 2; i < 1001000; i++) 25 if(prime[i])p[cnt++] = i; 26 } 27 28 int main() 29 { 30 char str[110]; 31 int x, num[10010]; 32 prime_init(); 33 while(scanf("%s %d", str, &x) != EOF) 34 { 35 if(!strcmp(str, "0") && x == 0)break; 36 int len = strlen(str); 37 int tmp = 0, k = 0; 38 for(int i = 0; i < len%3; i++) 39 tmp = tmp * 10 + str[i] - '0'; 40 num[k++] = tmp; 41 for(int i = len%3; i < len; i += 3) 42 { 43 tmp = 0; 44 for(int j = i; j < i+3; j++) 45 tmp = tmp * 10 + str[j] - '0'; 46 num[k++] = tmp; 47 } 48 bool flag = 0; 49 for(int i = 0; p[i] < x && !flag; i++) 50 { 51 tmp = 0; 52 for(int j = 0; j < k; j++) 53 tmp = (tmp * 1000 + num[j]) % p[i]; 54 if(tmp == 0) 55 { 56 flag = 1; 57 printf("%s %d\n", "BAD", p[i]); 58 } 59 } 60 if(!flag)printf("GOOD\n"); 61 } 62 return 0; 63 }