【题目解析】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
本題用了素數的快速判定。
具體原理見博客——>傳送門
#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; }
耗時:
總結
以上是生活随笔為你收集整理的【题目解析】1015 Reversible Primes (20 分)_27行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【解析】1013 Battle Over
- 下一篇: 【一遍过!!!】1014 Waiting