原题干:
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
题目大意:每一行给定两个数,如果第一个数为素数,并且第一个数在第二个数的进制下如果翻转后的十进制数仍然是素数,输出Yes,反之输出No
例如73 10,73是素数,73在10进制下翻转为37,仍然是素数,因此输出Yes。
而23 2中,23是素数,23在2进制下是10111,翻转后为11101,在十进制下为29,也是素数。所以输出Yes
这道题使用了除基取余法转化进制,传送门:C语言利用"除基取余法"转化进制 - 斐斐のBlog
代码如下:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
bool isPrime(int num){
if(num < 2 ) return false;
if(num == 2) return true;
for(int i = 2; i < num / 2; i++)
if(num % i == 0) return false;
return true;
}
int convert(int num, int d){
int arr[32] = {0};
//使用除基取余法转d进制
int len = 0;
do{
arr[len++] = num % d;
num /= d;
}while(num != 0);
//反转的同时转10进制
for(int i = len - 1; i >= 0; i--)
num += (arr[i] * pow(d, len - 1 - i));
return num;
}
int main(){
while(1){
int num, d;
cin >> num;
if(num < 0) break;
cin >> d;
if(isPrime(num) && isPrime(convert(num, d)))
cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}