题目
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
答案
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
int check(int tmp)
{
if(tmp==1||tmp==0) return 0;
else if(tmp==2) return 1;
for(int i=2;i<=sqrt(tmp)+1;i++)
{
if(tmp%i==0) return 0;
}
return 1;
}
int main()
{
while(1)
{
int num,radix;
vector<int> vec;
cin>>num;
if(num<0) break;
else cin>>radix;
int sum1=0,sum2=0;
while(num!=0)
{
vec.push_back(num%radix);
num/=radix;
}
for(int i=vec.size()-1;i>=0;i--)
sum1=sum1*radix+vec[i];
for(int i=0;i<vec.size();i++)
sum2=sum2*radix+vec[i];
int flag1=check(sum1),flag2=check(sum2);
if(flag1&&flag2) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
题目含义解析
这道题的意思是将输入的数字转换为对应进制的数,将转换后的结果以及其逆置的结果同时转回10进制,最后判断这两个十进制数是否为素数
还是不明白?我来给大家举个例子,就拿样例中的23 2
来说明最后的结果为什么是Yes?
- 我们先将23转为2进制,结果为10111
- 将10111逆置,得到结果11101
- 将10111和11101再转回十进制,得到结果为23和29
- 判断23和29是否为素数,很显然两个都是素数
- 输出Yes