码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 甲级 1015 Reversible Primes

时间:2018-09-18 19:56:00      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:put   --   case   nsis   tst   prime   htm   you   lse   

https://pintia.cn/problem-sets/994805342720868352/problems/994805495863296000

 

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

 

时间复杂度:$ O(\sqrt{N}) $

代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e5 + 10;

int prime(int x) {
    if(x == 1) return 0;
    if(x == 2) return true;
    for(int i = 2; i * i <= x; i ++)
        if(x % i == 0)
        return 0;
    return 1;
}

int main() {
    int N, D;
    int num[maxn];
    while(~scanf("%d", &N)) {
        if(!N) break;
        scanf("%d", &D);
        if(prime(N) == 0) {
            printf("No\n");
            continue;
        }
        else {
            int cnt = 0;
            do{
                num[cnt ++] = N % D;
                N /= D;
            }while(N);

            int sum = 0, k = 0;
            for(int i = cnt - 1; i >= 0; i --) {
                sum += num[i] * pow(D, k);
                k ++;
            }

            if(prime(sum))
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
    return 0;
}

  

PAT 甲级 1015 Reversible Primes

标签:put   --   case   nsis   tst   prime   htm   you   lse   

原文地址:https://www.cnblogs.com/zlrrrr/p/9670932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!