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

Posted bluebluesea

tags:

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

1015 Reversible Primes (20)(20 分)提问

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

radix是进制的意思,判断一个数是否是素数,如果不是则输出no,如果是则在D进制下进行Reverse,反转之后如果还是素数,那么就输出yes.

//如何求d进制的逆,参考:https://blog.csdn.net/sunbaigui/article/details/8657051

#include<iostream>
#include<stdio.h>
#include<math.h>
using  namespace std;
bool isPrime(int n){
    int m=sqrt(n);
    if(n==0||n==1)return false;
    for(int i=2;i<=m;i++){
        if(n%i==0)return false;
    }
    return true;
}
int rever(int n,int d){
//    string s="";求d进制,逆的方法
//    int m;
//    while(n!=0){
//        m=n%d;
//        n/=d;
//        s+=(m+‘0‘);
//    }
//    cout<<s<<" ";
//    n=0;
//    m=s.size();
//    for(int i=0;i<m;i++){
//        n=n*d+(s[i]-‘0‘);//这样求也是对的,但是明显比较复杂。
//    }
    int sum=0;
    do{
        sum=sum*d+n%d;//求逆!
        n/=d;
    }while(n!=0);
    return sum;
}

int main()
{
    int n,d;
    while(scanf("%d%d",&n,&d)!=1){
        //判断n是否是素数
        if(isPrime(n)){
            n=rever(n,d);
            if(isPrime(n))
                printf("Yes
");
            else
                printf("No
");
        }else
            printf("No
");
    }
    return 0;
}

1.求逆一个do-while循环太厉害了,注释掉的部分是我写的,不太对。

2.要注意特殊条件的判断,n==0||n==1直接返回false;不是素数,要不然,样例只能通过两个,另两个通不过!special case.

 

以上是关于PAT 1015 Reversible Primes[求d进制下的逆][简单]的主要内容,如果未能解决你的问题,请参考以下文章

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 分) 进制转换+质数