PAT 1015 Reversible Primes (判断素数)

Posted woxiaosade

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 1015 Reversible Primes (判断素数)相关的知识,希望对你有一定的参考价值。

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

思路

如果一个数为素数,且其在D进制下的反转过后的数字在10进制i下为素数,就输出Yes,否则输出No。

注意1为合数,1不是素数。会有一组数据关于这个的。

代码

#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <limits.h> 
using namespace std;
bool flag[500000];
void init(){
    flag[1] = 1;
    for(int i = 2; i * i < 500000; i++){
        if(!flag[i]){
            for(int j = i * i; j < 500000; j += i){
                flag[j] = 1;
            }
        }
    }
}

int getNum(int N, int D){
    string t = "";
    while(N != 0){
        t = t + char(N % D);
        N /= D;
    }
    long long sum = 0;
    int d = 1;
    for(int i = t.length() - 1; i >= 0; i--){
        sum += t[i] * d;
        d *= D;
    }
    return sum;
}

int main() {
    int N, D;
    init();
    while(cin >> N){
        if(N < 0)   return 0;
        cin >> D;
        getNum(N, D); 
        if(!flag[N] && !flag[getNum(N, D)]) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
    return 0; 
}

以上是关于PAT 1015 Reversible Primes (判断素数)的主要内容,如果未能解决你的问题,请参考以下文章

PAT1015:Reversible Primes

pat 1015 Reversible Primes(20 分)

PAT 甲级 1015 Reversible Primes

PAT 1015 Reversible Primes (判断素数)

PAT A1015 Reversible Primes (20 分)

PAT-1015 Reversible Primes (20 分) 进制转换+质数