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
代码:
扫描二维码关注公众号,回复:
2127587 查看本文章
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
#include <queue>
#include <cstring>
#include <map>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e5+5;
const ll INF = 0x3f3f3f3f;
const double eps=1e-4;
const int T=3;
bool isPrime[N];
int convert(int n,int r) {
int res=0;
while(n) {
res=res*r+n%r;
n/=r;
}
return res;
}
void is_prime() {
for(int i=2; i<N; i++) {
isPrime[i]=1;
}
for(int i=2; i*i<=N; i++) {
if(isPrime[i]) {
for(int j=i*i; j<=N; j+=i) {
isPrime[j]=0;
}
}
}
}
int main() {
int n,d;
is_prime();
while(cin>>n&&n>=0) {
cin>>d;
int res=convert(n,d);
if(isPrime[n]&&isPrime[res]) {
cout<<"Yes";
} else {
cout<<"No";
}
cout<<endl;
}
return 0;
}