题目
1015 Reversible Primes (20 分)
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 (<10
5
) 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
题目意思
输入一个n和m,然后问你n和转换为m制时的n是否都是素数,都是就输出Yes,否则输出No。
思路
该题的难点,应该是进制转换和素数判断。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
//判断素数
int hx(int i)
{
if(i==1)
return 0;
else if(i==2)
return 1;
else
{
for(int j=2; j<=sqrt(i); j++)
{
if(i%j==0)
return 0;
}
return 1;
}
}
//转换
int mz(int x,int m)
{
int a[16],i=0,q=0,sum=0;
while(x)
{
a[i++]=x%m;
x=x/m;
}
for (int j = i-1; j >= 0; j--)
sum += a[j]* pow(m, q++);
return sum;
}
int main()
{
int n,m;
while(~scanf("%d",&n))
{
if(n<0)
break;
scanf("%d",&m);
if(hx(n)&&hx(mz(n,m)))
printf("Yes\n");
else
printf("No\n");
}
return 0;
}