题目
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
-2
Sample Output:
Yes
Yes
No
题解
更新:AC版本
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(int n){
int sqr=int(sqrt(n));
if(n<=1) return false;
for(int i=2;i<=sqr;i++){
if(n%i==0) return false;
}
return true;
}
int reverse(int n,int d){
int arr[100];
int len=0;
int sum=0;
int r=1;
while(n!=0){
arr[len++]=n%d;
n/=d;
}
for(int i=len-1;i>=0;i--){
sum+=arr[i]*r;
r*=d;
}
return sum;
}
int main(){
int n,d,ans;
while(scanf("%d",&n)!=EOF){
if(n<=0) break;//题目要求为负数,终止整个循环
scanf("%d",&d);
if(isPrime(n)==false){
printf("No\n");
continue;//提前结束此次循环
}
ans=reverse(n,d);
if(isPrime(ans)) printf("Yes\n");
else printf("No\n");
}
return 0;
}
未AC版本
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(int n){
int sqr=int(sqrt(n));
if(n<=1) return false;
for(int i=2;i<=sqr;i++){
if(n%i==0) return false;
}
return true;
}
int main(){
int n,d;
int sum=0;
int r=1;
while(scanf("%d",&n)!=EOF){
if(n<=0) break;//题目要求为负数,终止整个循环
scanf("%d",&d);
if(isPrime(n)==false){
printf("No\n");
continue;//提前结束此次循环
}
int arr[100];
int len=0;
while(n!=0){
arr[len++]=n%d;
n/=d;
}
for(int i=len-1;i>=0;i--){
sum+=arr[i]*r;
r*=d;
}//主要就是这边的原因,使得两测试点过不去
if(isPrime(sum)) printf("Yes\n");
else printf("No\n");
}
return 0;
}
一开始我在想,D是否就是N的进制,直接把N倒过来,再转10进制。然后发现第二行23后跟着2,这时必须果断猜测,是要把10进制的N转成D进制再倒过来,再转10进制。
我觉得可能要更注意变量要处在合适的位置,以及函数功能方面,能分模块写就分模块写。