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 (<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
题目的意思是,先判断n是不是一个素数,同时将n变成d进制的数,然后将这个数颠倒,然后将这个数变成10进制数,在判断这个数是否是一个素数。
我的方法是:先用取对数(换底公式)的方法先确定转化成d进制的位数,这样在转化的同时我们也就可以求除颠倒以后的10进制数,说起来比较难懂,直接看代码估计更容易理解。
int to_d(int n, int r) {
int cnt = log(n)/log(r); //利用换底公式来求位数
int num = 0;
for (int i = cnt; i >= 0; i--) {
num += (n % r) * pow(r,i);
n /= r;
}
return num;
}
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int book[100001];
void getprime(int n) {
book[1] = book[0] = 1;
for (int i = 2; i <= n;i ++) {
if (book[i] == 0) {
for (int j = i + i; j <= n; j += i) {
book[j] = 1;
}
}
}
}
int to_d(int n, int r) {
int cnt = log(n)/log(r);
int num = 0;
for (int i = cnt; i >= 0; i--) {
num += (n % r) * pow(r,i);
n /= r;
}
return num;
}
int main () {
getprime(100001);
int n, d;
while(true) {
cin >> n;
if (n < 0) {
break;
} else {
cin >> d;
}
int tem = to_d(n, d);
if (book[n] == 0 && book[tem] == 0) {
cout << "Yes" << '\n';
} else {
cout << "No" << '\n';
}
}
return 0;
}