PAT Advanced 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 (<) and D (1), 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
 
 主要 考察进制转换
#include <iostream>
#include <string>
using namespace std;
bool isPrime(int N){
    if(N <= 1) return false;
    if(N == 2 || N == 3) return true;
    for(int i = 2; i * i <= N; i++)
        if(N % i ==0) return false;
    return true;
}
int rev(int N, int radix){
    string s = "";
    while(N != 0){
        s += (N % radix);
        N /= radix;
    }
    int p = 1, res = 0;
    for(int i = s.length()-1; i >= 0; i--){
        res += (s[i] * p);
        p *= radix;
    }
    return res;
}
int main(){
    int num, radix;
    while(true){
        cin >> num;
        if(num < 0) break;
        else {
            cin >> radix;
            int rev_num = rev(num, radix);
            if(isPrime(num) && isPrime(rev_num))
                cout << "Yes" << endl;
            else cout << "No" << endl;
        }
    }
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/littlepage/p/12259832.html