PAT A1015 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 (< 1 0 5 10^5 ) and D ( 1 < D 10 1<D\leq 10 ), you are supposed to tell if N N is a reversible prime with radix D D .

Input Specification:

The input file consists of several test cases. Each case occupies a line which contains two integers N N and D. The input is finished by a negative N N .

Output Specification:

For each test case, print in one line Yes if N N is a reversible prime with radix D D , or No if not.

Sample Input:

73 10
23 2
23 10
-2

Sample Output:

Yes
Yes
No

题意

质数 N N 转化为 D 进制之后再反转再转化为十进制之后结果也是一个质数即为一个可逆质数

思路1

  1. 判断素数模板
  2. 进制转换过程中得到的最低位就是反转之后的最高位,因此可以一边分离数位(进制转换),一边使用秦九韶算法将结果加到最后的结果上面 r = r * d + n % d;

代码1

#include <iostream>
using namespace std;
typedef long long LL;

bool is_prime(int x)
{
    if(x < 2) return false;
    for(int i = 2; i <= x / i; i++)
    {
        if(x % i == 0)
            return false;
    }
    return true;
}

bool check(int n, int d)
{
    if(!is_prime(n)) return false;
    LL r = 0;
    while(n)
    {
        r = r * d + n % d;
        n /= d;
    }
    return is_prime(r);
}

int main()
{
    int n, d;
    while(cin >> n >> d, n > 0)
    {
        if(check(n, d)) puts("Yes");
        else puts("No");
    }
    return 0;
}
发布了166 篇原创文章 · 获赞 27 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/HdUIprince/article/details/105463751
今日推荐