PAT 甲级 1015 Reversible Primes

Posted zlrrrr

tags:

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

https://pintia.cn/problem-sets/994805342720868352/problems/994805495863296000

 

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

 

时间复杂度:$ O(sqrt{N}) $

代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e5 + 10;

int prime(int x) {
    if(x == 1) return 0;
    if(x == 2) return true;
    for(int i = 2; i * i <= x; i ++)
        if(x % i == 0)
        return 0;
    return 1;
}

int main() {
    int N, D;
    int num[maxn];
    while(~scanf("%d", &N)) {
        if(!N) break;
        scanf("%d", &D);
        if(prime(N) == 0) {
            printf("No
");
            continue;
        }
        else {
            int cnt = 0;
            do{
                num[cnt ++] = N % D;
                N /= D;
            }while(N);

            int sum = 0, k = 0;
            for(int i = cnt - 1; i >= 0; i --) {
                sum += num[i] * pow(D, k);
                k ++;
            }

            if(prime(sum))
                printf("Yes
");
            else
                printf("No
");
        }
    }
    return 0;
}

  

以上是关于PAT 甲级 1015 Reversible Primes的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1015. Reversible Primes

PAT1015:Reversible Primes

pat 1015 Reversible Primes(20 分)

PAT 1015 Reversible Primes (判断素数)

PAT A1015 Reversible Primes (20 分)

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