码迷,mamicode.com
首页 > 其他好文 > 详细

PTA(Advanced Level)1015.Reversible Primes

时间:2020-03-19 22:04:02      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:positive   sqrt   思路   cout   als   who   ace   sed   not   

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

标签:positive   sqrt   思路   cout   als   who   ace   sed   not   

原文地址:https://www.cnblogs.com/MartinLwx/p/12527248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!