题目链接
题目描述
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 (< 1 0 5 10^5 105) and D (1<D≤10), you are supposed to tell if N is a reversible prime with radix D.
个人想法:
题目大意是:给出一个数,要求判断在指定 radix 下的表达方式翻转后根据该 radix 转换成为10进制是否为素数。
- 给出数字是否为素数要判断
- 0 和 1 不是素数
代码:
#include<iostream>
#include<algorithm>
using namespace std;
int cal(string n, int radix)
{
int val = 0;
for(auto t: n)
val = val * radix + t - '0';
return val;
}
string trans(int n, int radix){
string res;
while(n) {
res = (char)(n % radix + '0') + res;
n /= radix;
}
return res;
}
bool is_p(int x)
{
if(x < 2) return false;
for(int i = 2; i <= x / i; i++)
if(x % i == 0) return false;
return true;
}
string rev(string s)
{
for(int i = 0, j = s.length() - 1; i <= j; i++, j--)
{
char t;
t = s[i];
s[i] = s[j];
s[j] = t;
}
return s;
}
int main()
{
int n, d;
while(1) {
scanf("%d", &n);
if(n < 0) break;
scanf("%d", &d);
string str = trans(n, d);
string re_str = rev(str);
if(is_p(n) && is_p(cal(re_str, d))) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}