题目描述
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
题目要求总结
题目要求我们输入n对数以及他的进制,然后判断这个数反过来是否为素数,如果是,则输出yes,否则输出no,重点在于搞清楚如何将不同进制数转过来的意思
例:23 2
这里的23转换成二进制就变成10111,倒序就变为11101,再转成2进制即为29,23和29均为素数,故输出yes
另外这里在最开始的时候使用了生成素数表的方法直接用于下面的判断,素数表如何生成请参考我之前发布的文章判断素数的几种方法总结
AC代码
#include<stdio.h>
#include<stdlib.h>
const n = 100010;
bool p[n] = {false};
void Find_prime(){
p[0] = p[1] = true;
for(int i = 2; i < n; i++){
if(p[i] == false){
for(int j=i+i;j<n;j+=i)
{
p[j]=true;
}
}
}
}
int convert(int x, int d){
int dRadix[40], i = 0, result=0, product = 1;
while(x != 0){
dRadix[i++] = x % d;
x /= d;
}
for(int j = i-1; j >= 0; j--){
//printf("%d\n", dRadix[j]);
result += dRadix[j] * product;
product *= d;
}
return result;
}
int main(){
int n,d;
Find_prime();
while(scanf("%d", &n)){
if(n < 0)
break;
scanf("%d", &d);
int res = convert(n, d);
//以下这个判断语句要注意,需要同时满足原来的数和倒序后的数都是素数才可以输出yes
if(p[res] == false && p[n] == false) printf("YES\n");
else printf("NO\n");
}
//printf("%d", convert(23,2));
return 0;
}```