1015 Reversible Primes
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
分析:如果一个数(10进制数)本身是素数,它在D进制下的反转数为v,如果v也为素数,那么可以称这个数为“ reversible prime ”。
如23 2 十进制数23(10)转换为二进制数10111(2),反转后变成11101(2) 转换为10进制为29,29是素数
参考代码:
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
bool isprime(int n) {
if (n <= 1)return false;
int k = sqrt(n);
for (int i = 2; i <= k; i++) {
if (n%i == 0)return false;
}
return true;
}
int main() {
int n, flag, D;
while (scanf_s("%d%d", &n, &D) != EOF)
{
if (n < 0)break;
flag = 1;
if (!isprime(n)) { printf("No\n"); flag = 0; }
if (flag) {
int a[120], len = 0;
do {
a[len++] = n % D;
n /= D;
} while (n != 0);
for (int i = 0; i < len; i++) {
n = n * D + a[i];
}
printf("%s\n", isprime(n) ? "Yes" : "No");
}
}
return 0;
}