A reversible prime in any number system is a prime whose "reverse" in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a prime.
Now given any two positive integers N (< 105) and D (1 < D <= 10), you are supposed to tell if N is a reversible prime with radix D.
Input Specification:
The input file consists of several test cases. Each case occupies a line which contains two integers N and D. The input is finished by a negative N.
Output Specification:
For each test case, print in one line "Yes" if N is a reversible prime with radix D, or "No" if not.
Sample Input:73 10 23 2 23 10 -2Sample Output:
Yes Yes No
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 using namespace std; 6 7 char *itoa(int x, char *s, int r){//itoa并非标准C库函数 8 int idx = 0; 9 while(x > 0){ 10 s[idx ++] = x % r + '0'; 11 x /= r; 12 } 13 s[idx] = '\0'; 14 reverse(s, s+strlen(s)); 15 return s; 16 } 17 18 int atoi(char *s, int r){ 19 //reverse(s, s+strlen(s)); 20 int idx = 0, ret = 0; 21 while(s[idx]){ 22 ret *= r; 23 ret += s[idx ++]-'0'; 24 } 25 return ret; 26 } 27 28 bool isPrime(int x){ 29 if(x <= 1) return false; 30 int t = sqrt(x) + 1; 31 for(int i = 2; i < t; i ++){ 32 if(x % i == 0) return false; 33 } 34 return true; 35 } 36 37 int main() 38 { 39 int n, r; 40 char buf[100]; 41 while(1 == scanf("%d", &n)){ 42 if(n < 0) break; 43 scanf("%d", &r); 44 if(isPrime(n)){ 45 itoa(n, buf, r); 46 reverse(buf, buf+strlen(buf)); 47 int t = atoi(buf, r); 48 if(isPrime(t)) printf("Yes\n"); 49 else printf("No\n"); 50 51 }else printf("No\n"); 52 } 53 return 0; 54 }