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 "); 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 "); else printf("No "); } } return 0; }