PAT1015:Reversible Primes

Posted 0kk470

tags:

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

1015. Reversible Primes (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

思路

1.先判断十进制数N是否是素数,不是直接输出No。
2.如果N是素数先把N转为D进制数N1,然后得到的D进制数N1按颠倒的位数转换成十进制数N2,检查N2是否是素数即可。
例:
1)比如输入N = 23、D = 2,23是素数,那么23转2进制数为10111,颠倒后为11101,11101转换为十进制数后为29,29也是素数,输出Yes。
2)又比如N = 23,D = 6 , 23转6进制数为35,颠倒后为53,53转10进制数为33,33不是素数,输出No。

代码
#include<iostream>
#include<vector>
using namespace std;

bool isPrime(const int num)
{
    if(num != 2 && num % 2 == 0 || num == 1)
        return false;
    for(int i = 2;i * i <= num;i++)
    {
        if(num % i == 0)
            return false;
    }
    return true;
}

int main()
{
    int N;
    while(cin >> N)
    {
        if(N < 0)
            break;
        int D;
        cin >> D;
        if(!isPrime(N))
        {
            cout << "No" << endl;
            continue;
        }
        vector<int> digit(100,0);
        int index = 0;
        while( N != 0)
        {
            digit[index++] = N % D;
            N /= D;
        }
        for(int i = 0;i < index;i++)
        {
            N = N * D + digit[i];
        }
        if(isPrime(N))
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
    }
}

 

以上是关于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 分) 进制转换+质数

PAT1015. Reversible Primes