【題目解析】1015 Reversible Primes (20 分)_27行程式碼AC
立志用最少的程式碼做最高效的表達
PAT甲級最優題解——>傳送門
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
題意:如果數n是素數, 將n轉化成d進位制數,翻轉後在轉換回來, 判斷是否為負數。
舉例:輸入23 2
- 23為素數,繼續
- 23轉為二進位制:10111
- 10111翻轉:11101
- 11101轉回十進位制:29
- 29為素數,輸出Yes
本題用了素數的快速判定。
具體原理見部落格——>傳送門
#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n) {
if(n == 0 || n == 1) return false;
if (n == 2) return true;
if(n%6 != 1 && n%6 != 5) return false; //不在6的周圍一定不是
int temp = sqrt(n); //在6的周圍也可能不是
for(int i = 5; i <= temp; i += 6)
if(n%i==0 || n%(i+2)==0) return false;
return true;
}
int main() {
int n, d; while(cin>>n && n>=0 && cin>>d) {
int n1 = n;
string s;
while(n1) {
s += (char)(n1%d+'0');
n1 /= d;
}
int sum = 0, siz = s.size()-1;
for(auto i : s)
sum += (i-'0')*pow(d, siz--);
cout << ((isPrime(n) && isPrime(sum)) ? "Yes" : "No") << '\n';
}
return 0;
}