题目
判断一个进制数是否为素数,他的逆数是否为素数。
代码思路
题目考查进制转换和一个数逆序,很简单,但是不知道为什么最后一个点过不去,0 1 2都试过了也过不去。。。代码恨冗余,可以优化的更好。
#include<cstdio>
#include<stack>
#include<queue>
#include<math.h>
using namespace std;
int num;
int radix;
bool test1, test2;
int Ten, Rad;
int TenToRadix(int num){
stack<int> v;
int temp;
int result = 0;
while (num > 0) {
temp = num % radix;
num /= radix;
v.push(temp);
}
while (!v.empty()) {
temp = v.top();
v.pop();
result = result * 10 + temp;
}
return result;
}
int RadixToTen(int num){
int temp;
int result = 0;
int ex = 0;
while (num > 0) {
temp = num % 10;
num /= 10;
result += temp * pow(radix, ex);
ex++;
}
return result;
}
bool isPrime(int Num){
if (Num <= 1) return false;
int sqr = (int)sqrt(1.0 * Num);
for (int i = 2; i <= sqr; i++) {
if (Num % i == 0) return false;
}
return true;
}
int reverseNum(int Num) {
int temp;
int result = 0;
queue<int> q;
while (Num > 0) {
temp = Num % 10;
Num /= 10;
q.push(temp);
}
while (!q.empty()) {
temp = q.front();
q.pop();
result = result * 10 + temp;
}
return result;
}
int main() {
int temp;
bool result;
while (true) {
scanf("%d", &num);
if (num < 0) {
return 0;
}
scanf("%d", &radix);
test1 = isPrime(num);
Rad = TenToRadix(num);
temp = reverseNum(Rad);
Ten = RadixToTen(temp);
test2 = isPrime(Ten);
result = test1 && test2;
if (result == true) {
printf("Yes\n");
}
else
printf("No\n");
}
return 0;
}