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
思路:先判断自身是否是素数,再转换为对应进制的数,再判断是否是素数。
1 #include <iostream> 2 #include <string.h> 3 #include <cstring> 4 #include <algorithm> 5 #include <cstdio> 6 #include <stack> 7 using namespace std; 8 int n,d; 9 int _prime(int x) 10 { 11 if(x==1) return 0; 12 int flag=1; 13 for(int i=2;i*i<=x;i++){ 14 if(x%i==0){ 15 flag=0; 16 break; 17 } 18 } 19 return flag; 20 } 21 int _deal(int n,int d) 22 { 23 stack<int> s; 24 while(n){ 25 s.push(n%d); 26 n/=d; 27 } 28 int sum=0,t=1; 29 while(!s.empty()){ 30 sum+=s.top()*t; 31 t*=d; 32 s.pop(); 33 } 34 return sum; 35 } 36 int main() 37 { 38 while(cin>>n&&n>0){ 39 cin>>d; 40 int flag; 41 if(!_prime(n)) flag=0; 42 else{ 43 if(_prime(_deal(n,d))) flag=1; 44 else flag=0; 45 } 46 if(flag) cout<<"Yes"<<endl; 47 else cout<<"No"<<endl; 48 } 49 return 0; 50 }