题目
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
-2
Sample Output:
Yes
Yes
No
题目分析
可翻转质数:十进制中的质数,转换为指定进制并反转后的数字仍然是质数
已知十进制数,和指定进制,判断是否为可翻转质数
解题思路
- 判断输入的十进制数是否为质数
- 将输入的十进制数转换为指定进制数A
- 反转A得到B,判断B是否为质数
易错点
- 题目已知条件中数字为十进制,而不是指定进制下的数,虽然题目中未说明,但是可以从样例中23不可能是2进制判断出
知识点
- 题目没有给出样例数,输入非负数终止,该情况下的接收代码
while(scanf("%d",&n)!=EOF){
if(n<0)break;
}
Code
Code 01
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
bool isPrime(int n) {
if(n<=1)return false;
int sqr=(int)sqrt(1.0*n);
for(int i=2; i<=sqr; i++) {
if(n%i==0)return false;
}
return true;
}
int main(int argc, char * argv[]) {
int n,radix;
while(scanf("%d",&n)!=EOF) {
if(n<0)break;
scanf("%d",&radix);
if(isPrime(n)==false){
printf("No
");
continue;
}
// 进制转换
// 十进制数转换为指定的radix进制
int index=0,d[111]={0};
do{
d[index++]=n%radix;
n/=radix;
} while(n!=0);
// 逆置的radix进制数转换为十进制数
for(int i=0;i<index;i++){
n=n*radix+d[i];
}
if(isPrime(n))printf("Yes
");
else printf("No
");
}
return 0;
}