1015 Reversible Primes (20)(20 分)
作者: CHEN, Yue
单位: PAT联盟
时间限制: 400ms
内存限制: 64MB
代码长度限制: 16KB
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 (< 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
首先,这道题对我来说有那么一些过不去的地方是英语,这边做个记录吧:
decimal adj. 小数的;十进位的 n. 小数
这里最重要的是他有十进制的意思
reversible adj. 可逆的;可撤消的;可反转的 n. 双面布料
radix n. 根;[数] 基数
radix是基数的意思,也就是几进制的数,开始的时候还没反应过来基数是什么意思
英文关过了之后整道题逻辑还是比较简单的
判断 N 是不是素数 ----> 对N进行D进制转换 -----> 翻转后转换为十进制 -----> 判断翻转后是不是素数
这里我的认识产生了一个漏洞,就是N是翻转素数的条件不仅是他翻转之后是素数,N本身也要是一个素数,翻转素数的条件才成立,所以第一点就要判断N是否为素数,如果不是就可以直接输出了。
其他的步骤都是常规套路,但是在这里记录一下我犯的另一个错误:
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;
}
如有错误,欢迎指摘。