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和一个进制d,首先把n转换成d进制数,存在整型数组里,然后逆序在转换成十进制数,比较这两个十进制数是否是素数。我用一种比较高效的方法先找出[1,100000)里所有的素数,存在一个大小为100000的数组里,为素数则对应的值存为1,合数则为0。具体算法见注释。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int prime[100000] = {0};
int n, d, i, j;
for(i = 1; i < 100000; i += 2) //先将所有奇数置为1,为了便于理解,从1开始,其实可以从3开始
prime[i] = 1;
prime[2] = 1;
prime[1] = 0; //特殊情况的赋值
for(i = 2; i <= sqrt(100000); i++) //找出100000以内所有的素数
{
if(prime[i] == 1)
{
for(j = 2 * i; j < 100000; j += i)
prime[j] = 0;
}
}
while(1) //核心算法
{
scanf("%d", &n);
if(n < 0) //输入负数则算法结束
break;
scanf("%d", &d);
int s[100] = {0}; //存储每一位
int tmp = n, sum = 0;
i = -1;
while(tmp) //提取每一位,注意这里从下标0开始存进去就已经反向了
{
s[++i] = tmp % d;
tmp /= d;
}
for(j = 0; j <= i; j++) //还原为十进制数
{
sum = sum * d + s[j];
}
if(prime[n] == 1 && prime[sum] == 1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}