PAT 1015
代码
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<stdlib.h> // c库 标准库
using namespace std;
bool isPrime(int n){
if(n==1){
return false;
}
for(int i = 2; i <= n / 2; ++i)
{
if(n % i == 0)
{
return false;
}
}
return true;
}
string itos(int n,int d){
string result="";
do{
if(n%d>=10){
result+='a'+n%d-10;
}
else{
result+=to_string(n%d);
}
n=n/d;
}while(n!=0);
reverse(result.begin(),result.end());
return result;
}
int main(){
int n,d;
vector<string> result;
while(cin>>n){
if(n<0){
break;
}
cin>>d;
string str_n = itos(n,d);
reverse(str_n.begin(),str_n.end());
// reverse
int n_reverse = stoi(str_n,nullptr,d);
// string to int
// cout<<n<<" reverse: "<<n_reverse<<endl;
if(isPrime(n)&&isPrime(n_reverse)){
result.push_back("Yes");
}
else{
result.push_back("No");
}
};
for(int i=0;i<result.size();i++){
cout<<result[i]<<endl;
}
return 0;
}
解题思路
进制转换可以用itoa,stoi函数
pat网站不支持itoa,因为itoa是windows平台的
本题可以使用正常进制转换的除余取倒数的方法来做
本解题方法使用了通用的进制转换函数
测试点问题
1不是质数,需要考虑此情况