1.题目
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
2.题目分析
先看给出的第一个数是不是素数,不是就输出NO,是的话再将这个数按照后面的进制要求转换为相应进制下的数,将这个数reverse一下,再转为十进制看是不是素数,是的话就是yes
3.代码
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
bool isprime(int t)
{
if (t == 0 || t == 1)return false;
for (int i = 2; i <= sqrt(t); i++)
if (t%i == 0)return false;
return true;
}
int changea(string a,int d)//其它进制转十进制
{
int num = 0;
for (int i = 0; i < a.length(); i++)
num += (a[i] - '0')*pow(d, a.length() - i - 1);
return num;
}
string changeb(int num,int d )//十进制转其它进制
{
string answer = "";
int out[110];
int s = 0;
while (num > 0)
{
out[s++] = num%d;
num /= d;
}
for (int i = s - 1; i >= 0; i--)
answer += out[i] + '0';
reverse(answer.begin(), answer.end());
return answer;
}
int main()
{
string a, b;
while (1)
{
cin >> a;
if (stoi(a) < 0)return 0;
cin >> b;
if (!isprime(stoi(a))) { printf("No
"); continue; }
if(!isprime(changea(changeb(stoi(a),stoi(b)),stoi(b)))) { printf("No
"); continue; }
printf("Yes
");
}
}