PTA(Advanced Level)1015.Reversible Primes

Posted martinlwx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PTA(Advanced Level)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)下是否为素数

  • 检查素数的方法和根据进制反转没有什么好讲的,挺简单的
  • 值得一提的是本身不是素数就没必要再进行反转了
代码
#include<bits/stdc++.h>
using namespace std;
bool is_prime(int x)
{
    if(x <= 1)  return false;
    int up = (int)sqrt(x * 1.0);
    for(int i=2;i<=up;i++)
        if(x % i == 0)
            return false;
    return true;
}   //判断素数的方法

int getR(int n, int d)
{
    vector<int> v;
    int t = 0;
    while(n)
    {
        t = n % d;
        v.push_back(t);
        n /= d;
    }
    int r_value = 0;
    for(int i=0;i<v.size();i++)
    {
        r_value += v[i] * pow(d, v.size() - i - 1);
    }
    return r_value;
}   //根据进制得到反转之后的值

int main()
{
    int n, d;
    while(cin >> n)
    {
        if(n < 0)   break;
        else    cin >> d;
        if(!is_prime(n))    //如果本身不是素数,没有进一步检查的必要
        {
            cout << "No" << endl;
            continue;
        }
        else
        {
            int reverse_value = getR(n,d);
            if(is_prime(reverse_value))
                cout << "Yes" << endl;
            else cout << "No" << endl;
        }
    }
    return 0;
}
引用

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

以上是关于PTA(Advanced Level)1015.Reversible Primes的主要内容,如果未能解决你的问题,请参考以下文章

PTA(Advanced Level)1025.PAT Ranking

PTA (Advanced Level)1022 Digital Library

PTA(Advanced Level)1059.Prime Factors

PTA(Advanced Level)1044.Shopping in Mars

PTA(Advanced Level)1036.Boys vs Girls

PTA (Advanced Level)1013 Battle Over Cities