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
题意:
给出正整数N和进制radix,如果N(<105)是素数,且N在radix(1<D≤10)进制下反转后的数在十进制下也是素数,则输出 Yes,否则输出 No。当输入的N为负数时,结束输入。
知识点:
- while...EOF 型:scanf函数的返回值为其成功读入参数的个数。对于正常控制台中的输入一般不会失败,只有在读取文件时,到达文件末尾导致无法读取现象,才会产生读入失败。这是,scanf函数会返回-1,而不是0,使用EOF(End of File)来表示 -1。即就是说,当题目没有说明有多少数据需要读入时,就可以利用scanf函数的返回值是否为EOF来判断输入是否结束。
思路:
进制转化类型题目常规实现参考:B1022 D进制的A+B
先判断N是否为素数,再转换进制,因为转换进制后数字变为存储于 int 型数组中是数(而且此时数字从低到高为反序),因此直接计算该数对应的十进制数,再此判断是否为素数,如全部满足,输出Yes即可。
#include <cstdio>
#include <cmath>
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 d[111];
int main(){
int n, radix;
while(scanf("%d", &n) != EOF){
if(n < 0)
break;
scanf("%d", &radix);
if(isPrime(n) == false)
printf("No\n");
else{
int len = 0;
do{
d[len++] = n % radix;
n /= radix;
}while(n != 0); //此时数字从低到高为逆序
for(int i = 0; i < len; i++){ //逆序转化为十进制
n = n * radix + d[i];
}
if(isPrime(n) == true)
printf("Yes\n");
else
printf("No\n");
}
}
return 0;
}