1015 Reversible Primes (20)(20 分)提问
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
radix是进制的意思,判断一个数是否是素数,如果不是则输出no,如果是则在D进制下进行Reverse,反转之后如果还是素数,那么就输出yes.
//如何求d进制的逆,参考:https://blog.csdn.net/sunbaigui/article/details/8657051
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
bool isPrime(int n){
int m=sqrt(n);
if(n==||n==)return false;
for(int i=;i<=m;i++){
if(n%i==)return false;
}
return true;
}
int rever(int n,int d){
// string s="";求d进制,逆的方法
// int m;
// while(n!=0){
// m=n%d;
// n/=d;
// s+=(m+'0');
// }
// cout<<s<<" ";
// n=0;
// m=s.size();
// for(int i=0;i<m;i++){
// n=n*d+(s[i]-'0');//这样求也是对的,但是明显比较复杂。
// }
int sum=;
do{
sum=sum*d+n%d;//求逆!
n/=d;
}while(n!=);
return sum;
} int main()
{
int n,d;
while(scanf("%d%d",&n,&d)!=){
//判断n是否是素数
if(isPrime(n)){
n=rever(n,d);
if(isPrime(n))
printf("Yes\n");
else
printf("No\n");
}else
printf("No\n");
}
return ;
}
1.求逆一个do-while循环太厉害了,注释掉的部分是我写的,不太对。
2.要注意特殊条件的判断,n==0||n==1直接返回false;不是素数,要不然,样例只能通过两个,另两个通不过!special case.