# PAT A 1015（甲级）

1015 Reversible Primes (20)（20 分）

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 (< 10^5^) 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
-2

Sample Output:

Yes
Yes
No

bool isPrime(int a) {
if(a <= 1) {
return false;
}
int sa = (int)sqrt(a * 1.0);
for(int i = 2; i <= sa; ++i) {
if(a % i == 0) {
return false;
}
}

return true;
}

在判断素数的函数中，千万要注意是 i <= sa，而不是 i < sa，这个细节错误困扰了我很久，因为可能到sa的时候才能判断出他不是素数，比如 169，在i = 13的时候才判断返回 false。

AC代码：

#include <cstdio>
#include <math.h>

int rd[150];
int rdNum = 0;

bool isPrime(int);
void tenToTarAndRev(int, int);
int tarToTen(int);

int main() {
int n, d;
while(scanf("%d", &n) != EOF && n >= 0) {
scanf("%d", &d);
if(isPrime(n)) {
rdNum = 0;
tenToTarAndRev(n, d);
int p = tarToTen(d);
printf("%s\n", isPrime(p)? "Yes": "No");
} else {
printf("No\n");
}
}

return 0;
}

bool isPrime(int a) {
if(a <= 1) {
return false;
}
int sa = (int)sqrt(a * 1.0);
for(int i = 2; i <= sa; ++i) {
if(a % i == 0) {
return false;
}
}

return true;
}

void tenToTarAndRev(int p, int r) {
while(p != 0) {
rd[rdNum++] = p % r;
p /= r;
}
}

int tarToTen(int r) {
int result = 0;
for(int i = 0; i < rdNum; ++i) {
result = result * r + rd[i];
}

return result;
}