PAT Advanced 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 (<) and D (1), 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和其翻转是否均为素数。注意0、1在判定素数时的处理。
#include<bits/stdc++.h> using namespace std; int todec(string now,int radix) { int len=now.length(); int ans=0; for(int i=0;i<len;i++) { ans*=radix; ans+=now[i]-'0'; } return ans; } string toarb(int now,int radix) { stringstream buf; while(now!=0) { buf<<now%radix; now/=radix; } string ans; buf>>ans; reverse(ans.begin(),ans.end()); return ans; } bool check(int now) { if(now==0||now==1)return false; int up=sqrt(now); for(int i=2;i<=up;i++) { if(now%i==0) return false; } return true; } int main() { string a,b; int N,D; while(cin>>N&&N>=0) { cin>>D; a=toarb(N,D); b=a; reverse(a.begin(),a.end()); //cout<<a<<' '<<b<<' '<<endl; if(check(todec(a,D))&&check(todec(b,D))) { cout<<"Yes"<<endl; }else { cout<<"No"<<endl; } } return 0; }