1015 Reversible Primes (20 point(s))
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
Tips:
(1)在D进制下把数字n反转:想一想是不是和在10进制下反转是一样的呢?并不用先转换为D进制,再反转,再转换为10进制。
(2)此题素数判断要求到了1e5,使用素数筛法会造成MLE。
#include<iostream>
using namespace std;
int reverse(int n,int d){//reverse any number with d redix
int ans = 0;
while(n){
ans = ans*d+n%d;
n/=d;
}
return ans;
}
bool isPrime(int x){//judge if it is a prime number
if(x<2) return false;
for(int i=2;i*i<=x;i++){
if(x%i==0) return false;
}
return true;
}
int main(void){
int n,d;
while(cin>>n){
if(n<0) break;
cin>>d;
if(isPrime(n)&&isPrime(reverse(n,d)))cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}
本文介绍了一种算法,用于判断一个给定的正整数N是否为D进制下的可逆素数,即N及其在D进制下的反转数均为素数。文章提供了输入输出规范、样例和代码实现,包括数字反转和素数判断两个关键函数。
253

被折叠的 条评论
为什么被折叠?



