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
质数的判断和进制转化。
//
// main.cpp
// Reversible_Prime
//
// Created by Hui Du on 2017/10/3.
// Copyright © 2017年 Hui Du. All rights reserved.
//
#include <iostream>
#include <math.h>
#include <cstdio>
using namespace std;
//判断是否为质数,循环到sqrt(num)就可以, 0,1都不是质数
int isPrime(int num){
int i;
if(num == 0 || num == 1){
return 0;
}
for(i = 2; i <= sqrt(num); i++){
if(num % i == 0){
return 0;
}
}
return 1;
}
//在固定进位条件下反转整数
int Revers(int N, int radix){
int sum = 0;
do{
sum = sum * radix + N % radix;
N = N/radix;
} while (N > 0);
//printf("sum: %d\n", sum);
return sum;
}
int main(int argc, const char * argv[]) {
int N = 0, radix;
while (N >=0) {
cin >> N;
if(N < 0){
break;
}
cin >> radix;
if(isPrime(N) && isPrime(Revers(N,radix))){
cout << "Yes\n";
}
else cout << "No\n";
}
return 0;
}