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
题目大意:
题目给出一个数以及一个进制,要求你判断该数是否为可逆素数。所谓可逆素数,即本身是素数,且转化为某个进制后进行翻转,仍为素数。
解题思路:
首先判断给出的数(十进制形式)是否为素数,若不是,则直接输出No;
将该数转化为题目给出的某种进制的形式,使用string存储进制位,因为转化进制的过程中本来就是翻转的,因此后面可省略翻转的步骤(转换进制时原本需要将得到的字符串翻转后才是正确的转换结果);
将转换后的数再转换为十进制,判断是否为素数(0和1既不是素数也不是合数)。
代码如下:
#include<iostream>
#include<cstdio>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
string changeToRadix(int number,int radix){
string s;
int a = number;
while(a){
s += (a % radix + '0');
a = a / radix;
}
return s; //本身就是翻转的形式,因此后面不需要再进行翻转
}
int changeToDecimal(string strNum,int radix){
int sum = 0;
for(int i = 0 ; i < strNum.length() ; i ++){
sum += (strNum[i]-'0') * pow(radix,strNum.length()-i-1);
}
return sum;
}
bool judge(int number){
if(number == 0 || number == 1)
return false;
for(int i = 2 ; i <= sqrt(number) ; i ++){
if(number % i == 0)
return false;
}
return true;
}
int main(){
int number,radix;
while(scanf("%d%d",&number,&radix) && number >= 0)
{
if(judge(number) == false)
printf("No\n");
else{
string strNum = changeToRadix(number,radix);//转化为D进制
int newNum = changeToDecimal(strNum,radix);
if(judge(newNum))
printf("Yes\n");
else
printf("No\n");
}
}
return 0;
}
可逆素数判断算法
本文介绍了一种算法,用于判断一个数在特定进制下是否为可逆素数。可逆素数是指一个素数在任何进制下翻转后仍然是素数。文章详细解释了算法的实现过程,包括如何将十进制数转换为指定进制,以及如何判断一个数是否为素数。
245

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



