题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1015
题目描述:
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 (< 105) 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 -2Sample Output:
Yes
Yes
No
分析:给出一个数N和一个基数D。首先这个数必须是素数。其次,将这个数(1)转为D进制数(2)将这个D进制数反转(3)将反转后的数再转为十进制数,这个十进制数依然是素数。 这样我们就输出“Yes”。
题目不难,就是表述不清楚,看的费劲。
将十进制数转为n进制数:(待补充。。。)
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
bool is_Prime(int a)
{
int i;
if(a==0 || a==1) return false;
//注意是i<=sqrt(),之前弄成i<sqrt,一直出错
for(i=2; i <= sqrt((double)a); i++){
if( a%i == 0) return false;
}
return true;
}
int change(int n,int d){
int a[100000];
memset(a,0,sizeof(a));
int total = 0;
int j;
int i;
for(i=0; ; i++){
a[i] = n%d;
n /= d;
if(n==0) break;
}
for(j=0; j<=i; j++)
{
total = total*d + a[j];
}
/*也可以这样写
do
{
total = total*d + n%d;
n/=d;
} while (n != 0);
*/
return total;
}
int main()
{
int N,D;
while(cin>>N){
if( N<0 ) break;
cin>>D;
if( is_Prime(N) && is_Prime( change(N,D) )){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
}
return 0;
}