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
大意:给定一个数和进制,在该进制下,该数逆序后是否还是素数。
1: 注意给定的数是10进制(我一直在想二进制数为什么是23),翻转在D进制下进行
2: 数的翻转有若干种做法:转为string再倒着加上来,或者使用秦九昭算法:
使用 for(Res=0;n;n/=D){Res=Res*D+n%D;}进行迭代。N会改变
3:不要忘记1不是素数
#include<iostream>
#include<vector>
using namespace std;
bool IsPrime(int x){
if(x==1) return false;
for(int i=2;i<x/2;i++){
if(x%i==0) return false;
}
return true;
}
vector<int> split(int N, int base){
vector<int> a;
for(;N;N/=base){
a.push_back(N%base);
}
return a;
}
int main(){
while(1){
int N,D;
cin>>N;
if(N<0) break;
cin>>D;
int Res=0;
int Base=1;
vector<int> a=split(N,D);
for(int i=a.size()-1;i>=0;i--){
Res+=a[i]*Base;
Base*=D;
}
if(IsPrime(N)&&IsPrime(Res)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
秦九昭算法,可以看出秦九昭算法不仅效率更高,而且更加简便
#include<iostream>
using namespace std;
bool IsPrime(int x){
if(x==1) return false;
for(int i=2;i<x/2;i++){
if(x%i==0) return false;
}
return true;
}
int main(){
while(1){
int N,D;
cin>>N;
if(N<0) break;
cin>>D;
int Res,Num=N;
for(Res=0;N;Res=Res*D+N%D,N/=D){}
if(IsPrime(Num)&&IsPrime(Res)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}