PAT 1015. Reversible Primes

Posted A-Little-Nut

tags:

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

PAT 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 (< 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

分析

先判断数是否是prime,然后化为radix进制,再反转,再化成十进制判断是不是prime;看了半天才明白什么意思

代码如下

#include<iostream>
#include<math.h>
using namespace std;
long long int toradix(long long n,long long int radix){
    string num;
    while(n!=0){
        num.insert(num.begin(),1,'0'+n%radix);
        n/=radix;
    }
    return stoll(num);
}
bool isprime(long long int num){
    if(num<=1) return false;
    for(int i=2;i<=sqrt(num);i++)
    if(num%i==0) return false;
    return true;
}
long long int toten(string n,long long int radix){
    long long int m=0,tag=0;
    for(int i=n.size()-1;i>=0;i--)
    m+=pow(radix,tag++)*(n[i]-'0');
    return m;
}
int main(){
    long long int radix,num,n;
    while(1){
    int flag=1; string m,s;
    cin>>n;
    if(n<0) return 0;
    cin>>radix;
    if(!isprime(n)) flag=0; 
    n=toradix(n,radix); 
    s=to_string(n);
    for(int i=s.size()-1;i>=0;i--)
    m.append(1,s[i]); 
    n=toten(m,radix);
    if(!isprime(n)) flag=0;
    flag>0?cout<<"Yes"<<endl:cout<<"No"<<endl;
    }
    return 0;
} 

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

PAT 1015 Reversible Primes[求d进制下的逆][简单]