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 (<) and D (1), 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、写判断素数函数不要忘记了判断1,1不是素数
  2、主要思路,先对n进行判断,如果n是素数再把n转化d进制数进行反转,再转化为10进制数进行判断是否是素数。
#include<iostream>
#include<sstream>
#include<algorithm>
#include<map>
#include<cmath>
#include<cstdio>
#include<string.h>
#include<queue>
using namespace std;
int a[1000000];
int length=0;



long long toD(int n,int d)
{
    int i=0;
    while(n>0)
    {
        int t=n%d;
        n=n/d;
        a[i]=t;
        i++;
    }
    length=i;
    long long int decimal=0;
    for(int i=0; i<length; i++)
    {
        decimal+=a[i]*pow(d,length-i-1);
    }
    return decimal;
}

bool isPrime(long long decimal)
{
    if(decimal==1)//不要完了对1做判断
        return false;
    for(int i=2; i<=sqrt(decimal); i++)
        if(decimal%i==0)
            return false;
    return true;
}

int main()
{
    int n,d;
    while(cin>>n)
    {
        if(n<0)
            break;
        cin>>d;
        long long decimal=toD(n,d);
       // cout<<decimal<<endl;
        if(isPrime(decimal)&&isPrime(n))
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    }

    return 0;
}
 
原文地址:https://www.cnblogs.com/zhanghaijie/p/10221866.html