1015 Reversible Primes (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 (<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
题型分类:进制转换、简单数学问题
题目大意:如果一个正整数是素数,并且他在进制D下的的字符串反转之后,再转换成十进制数也是素数的话,这个数就是reversible prime。
解题思路:分为三步模块化处理:
第一步将给定的数转换成D进制下的字符串(此字符串已经翻转);
第二步将翻转后的字符串转换成十进制数;
第三步判断原数字和处理后的数是否都为素数。
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
string convertToDRadix(int N, int D);
int convertToDecimal(string str, int D);
bool isPrime(int N);
int main(int argc, char** argv) {
int N, D, reverseN;
string str;
while(1){
scanf("%d", &N);
if(N < 0) break; //负数则表示输入结束
scanf("%d", &D);
str = convertToDRadix(N, D);
reverseN = convertToDecimal(str, D);
if(isPrime(N) && isPrime(reverseN)) printf("Yes\n");
else printf("No\n");
}
return 0;
}
string convertToDRadix(int N, int D){
string str;
do{ //注意得到的str已经是反转后的数
str += N % D + '0';
N /= D;
}while(N);
return str;
}
int convertToDecimal(string str, int D){
int sum = 0;
for(int i = 0; i < str.length(); i++){
sum = sum * D + str[i] - '0';
}
return sum;
}
bool isPrime(int N){
if(N <= 1) return false;
int sqr = sqrt(1.0 * N);
for(int i = 2; i <= sqr; i++){
if(N % i == 0) return false;
}
return true;
}