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 (<105) 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
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <algorithm> #include <iostream> #include <string.h> #include <queue> #include <string> using namespace std; const int maxn = 1010; int n, d; int to_10(int i,int radix) { int res = 0,exp=0; while (i != 0) { res += i%10*pow(radix, exp); exp++; i /= 10; } return res; } bool is_prime(int i) { if (i == 0 || i == 1)return false; if (i == 2 || i == 3)return true; for (int j = 2; j*j <= i; j++) { if (i%j == 0)return false; } return true; } string to_s(int i,int radix) { string s = ""; do { s += '0' + i % radix; i /= radix; } while (i != 0); reverse(s.begin(), s.end()); return s; } int to_num(string s) { int res = 0; for (int i = s.length()-1; i >=0; i--) { res = res * 10 + s[i] - '0'; } return res; } int main() { while (true) { scanf("%d", &n); if (n < 0)break; else { scanf("%d", &d); if (is_prime(n) && is_prime(to_10(to_num(to_s(n,d)), d))) printf("Yes\n"); else printf("No\n"); } } system("pause"); return 0; }
注意点:题目没看懂,导致结果一直错。题目的意思是一个10进制数如果他本身是素数,然后转换到给定进制下并将其反转,再转化到10进制,还是素数的话即为 Yes。
----------------
坚持每天学习一点点