PAT A1015 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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
#include <string>
using namespace std;
const int maxn = ;
int n, d;
int to_10(int i,int radix) {
int res = ,exp=;
while (i != ) {
res += i%*pow(radix, exp);
exp++;
i /= ;
}
return res;
}
bool is_prime(int i) {
if (i == || i == )return false;
if (i == || i == )return true;
for (int j = ; j*j <= i; j++) {
if (i%j == )return false;
}
return true;
}
string to_s(int i,int radix) {
string s = "";
do {
s += '' + i % radix;
i /= radix;
} while (i != );
reverse(s.begin(), s.end());
return s;
}
int to_num(string s) {
int res = ;
for (int i = s.length()-; i >=; i--) {
res = res * + s[i] - '';
}
return res;
}
int main() {
while (true) {
scanf("%d", &n);
if (n < )break;
else {
scanf("%d", &d);
if (is_prime(n) && is_prime(to_10(to_num(to_s(n,d)), d))) printf("Yes\n");
else printf("No\n");
}
}
system("pause");
return ;
}

注意点:题目没看懂,导致结果一直错。题目的意思是一个10进制数如果他本身是素数,然后转换到给定进制下并将其反转,再转化到10进制,还是素数的话即为 Yes。

上一篇:PTA编程总结2—币值转换


下一篇:PAT乙级:1088 三人行 (20分)