原题
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
题目翻译
在任何数制中,可逆质数是指在该数制中其 "f反转 "也是质数的质数。例如,在十进制中,73 是一个可逆质数,因为它的相反数 37 也是一个质数。
现在给定任意两个正整数 N (<105) 和 D (1<D≤10),你应该知道 N 是否是弧度为 D 的可逆质数。
输入规范:
输入文件由多个测试用例组成。每个案例占一行,包含两个整数 N 和 D。
输出说明:
对于每个测试用例,如果 N 是弧度为 D 的可逆质数,则在一行中打印 "Yes";如果不是,则打印 "No"。
解题思路
本题没什么难的,要注意的是1不是质数,否则测试点2过不了。
代码(c++)
#include <bits/stdc++.h>
using namespace std;
bool is_prime(int x){ // 判断是否为质数
if(x == 1) return false;
for(int i = 2; i <= x / i; i++)
if(x % i == 0) return false;
return true;
}
int reverse(int x, int radix){ // 反转
string str = "";
while(x != 0){ // 先转换为反转的radix进制,用str存储
str = str + to_string(x % radix);
x /= radix;
}
int res = 0, p = 1;
for(int i = str.size() - 1; 0 <= i; i--) { // 转换为10进制
res += (str[i] - '0') * p;
p *= radix;
}
return res;
}
int main(){
int a, b;
cin >> a;
while(a > 0){
cin >> b;
if(is_prime(a) && is_prime(reverse(a, b))) printf("Yes\n");
else printf("No\n");
cin >> a;
}
return 0;
}