首页 > 其他 > 详细

PAT 1015. Reversible Primes

时间:2018-01-05 22:25:31      阅读:279      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/A-Little-Nut/p/8207060.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!