PAT 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 (<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
思路
如果一个数为素数,且其在D进制下的反转过后的数字在10进制i下为素数,就输出Yes,否则输出No。
注意1为合数,1不是素数。会有一组数据关于这个的。
代码
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <limits.h>
using namespace std;
bool flag[500000];
void init(){
flag[1] = 1;
for(int i = 2; i * i < 500000; i++){
if(!flag[i]){
for(int j = i * i; j < 500000; j += i){
flag[j] = 1;
}
}
}
}
int getNum(int N, int D){
string t = "";
while(N != 0){
t = t + char(N % D);
N /= D;
}
long long sum = 0;
int d = 1;
for(int i = t.length() - 1; i >= 0; i--){
sum += t[i] * d;
d *= D;
}
return sum;
}
int main() {
int N, D;
init();
while(cin >> N){
if(N < 0) return 0;
cin >> D;
getNum(N, D);
if(!flag[N] && !flag[getNum(N, D)]) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}