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 NNN (<105< 10^5<105) and DDD (1<D≤101 < D \le 101<D10), you are supposed to tell if NNN is a reversible prime with radix DDD.

Input Specification:

The input file consists of several test cases. Each case occupies a line which contains two integers NNN and DDD. The input is finished by a negative NNN.

Output Specification:

For each test case, print in one line Yes if NNN is a reversible prime with radix DDD, or No if not.

Sample Input:

73 10
23 2
23 10
-2

Sample Output:

Yes
Yes
No

给两个数n,radix分别表示一个十进制数以及一个基数,判断一下该数转化为radix进制并反转后再化为十进制数,判断这两个数是否都为素数。Yes或No,当n为负数的时候结束输入。注意0与1输出No

思路:数据量在1e5以内,并且基数不会超过10,所以转化的数也不会超过maxn。然后 O ( 1 ) O(1) O(1)判断。

Code

#include <bits/stdc++.h>

using namespace std;
const int maxn = (int)1e5+5;

bool vis[maxn];
int prime[maxn], len;
void euler(int n) {
  memset(vis, false, sizeof(vis));
  vis[0] = vis[1] = true;
  int k, i, j;
  len = 0;
  for (i = 2; i <= n; i++) {
    if (!vis[i]) prime[++len] = i;
    for (j = 1; j <= len; j++) {
      k = i * prime[j];
      if (k > n) break;
      vis[k] = true;
      if (i % prime[j] == 0) break;
    }
  }
}

//将n转为m进制的反转数
int change(int n, int m) {
  int ans = 0;
  while (n > 0) {
    ans = ans * m + n % m;
    n /= m;
  }
  return ans;
}

int main() {
  int data,radix;
  euler(maxn-1);
  while (scanf("%d", &data) != EOF && data >= 0) {
    scanf("%d", &radix);
    if (!vis[data] && !vis[change(data, radix)]) {
      printf("Yes\n");
    } else {
      printf("No\n");
    }
  }
  return 0;
}