1015 Reversible Primes (20分)

1 题目

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

2 解析

2.1 题意

给出一个素数,判断在d进制下反转后在十进制下是否是素数,如果是,则输出"Yes",否,则输出"No"。

2.2 思路

  • 1 判断n是否是素数,如果不是,则输出“No”;如果是,则进入步骤二;
  • 2 把n转换为d进制,逆序把d进制的n转换为10进制的n,如果n是素数,输出"Yes";如果不是,则输出“No”;

3 参考代码

#include <cstdio>
#include <cmath>

int z[101];

bool isPrime(int n){//判断n是否是素数
    if(n <= 1) return false;
    int sqr = (int) sqrt(1.0 * n);
    for (int i = 2; i <= sqr; ++i)
    {
        if(n % i == 0) return false;
    }
    return true;
}

void Check(int n, int d){
    int zNum = 0;//长度
    do{//转换为p进制
        z[zNum++] = n % d;
        n /=d;
    }while(n != 0);

    for (int i = 0; i < zNum; ++i) {//逆序转为10进制
        n = n * d + z[i];
    }

    if(isPrime(n) == true){//是素数
        printf("Yes\n");
    }else{
        printf("No\n");
    }

}

int main(int argc, char const *argv[])
{
    int n, d;
    while(scanf("%d", &n) != EOF){
        if(n < 0){//是负数,则退出循环
            break;
        }
        scanf("%d", &d);
        if(isPrime(n) == false){
            printf("No\n");
        }else{
            Check(n, d);
        }
    }
    return 0;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页