天天看點

PAT甲級1015 Reversible Primes

題目

1015 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 (<10

​5

​​ ) 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

題目意思

輸入一個n和m,然後問你n和轉換為m制時的n是否都是素數,都是就輸出Yes,否則輸出No。

思路

該題的難點,應該是進制轉換和素數判斷。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>

using namespace std;

//判斷素數
int hx(int i)
{
    if(i==1)
        return 0;
    else if(i==2)
        return 1;
    else
    {
        for(int j=2; j<=sqrt(i); j++)
        {
            if(i%j==0)
                return 0;
        }
        return 1;
    }
}
//轉換
int mz(int x,int m)
{
    int a[16],i=0,q=0,sum=0;
    while(x)
    {
        a[i++]=x%m;
        x=x/m;
    }
    for (int j = i-1; j >= 0; j--)
        sum += a[j]* pow(m, q++);
    return sum;
}
int main()
{
    int n,m;
    while(~scanf("%d",&n))
    {
        if(n<0)
            break;
        scanf("%d",&m);
        if(hx(n)&&hx(mz(n,m)))
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}