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>
using namespace std;
const int maxn=100010;
bool p[maxn]={false};
void find_prime()
{
p[1]=true;//1不是素数也不是合数
for(int i=2;i<maxn;i++)
{
if(p[i]==false)
{
for(int j=i+i;j<maxn;j+=i)
p[j]=true;
}
}
}
void IsReversible(int N,int D)
{
int num[20],d1=0,d2=0,count=0;
while(N)
{
num[count++]=N%D;
N/=D;
}
for(int i=0;i<count;i++)
{
d1=d1*D+num[i];
d2=d2*D+num[count-1-i];
}
if(p[d1]==false&&p[d2]==false)
printf("Yes\n");
else
printf("No\n");
}
int main()
{
find_prime();
int N,D;
scanf("%d",&N);
while(N>=0)
{
scanf("%d",&D);
IsReversible(N,D);
scanf("%d",&N);
}
}