1015 Reversible Primes(20分)
阿新 • • 發佈:2022-05-31
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
一開始以為題目設定反向取值是為了設坑,但實際上是為了方便我們計算,在十進位制轉其他進位制時就不用反取餘數了
1 #include<bits/stdc++.h> 2 using namespace std; 3 int pow(int a,int n){ 4 int x=1; 5 for(int i=0;i<n;++i){ 6 x*=a; 7 } 8 return x; 9 } 10 bool JudgePrime(intx){ //判斷質數 11 if (x==1){ 12 return false; 13 } 14 else if (x==2){ 15 return true; 16 } 17 for (int i=2;i<=x/2+1;++i){ 18 if (x%i==0){ 19 return false; 20 } 21 } 22 return true; 23 } 24 int DtoX(int d,int x){ //轉x進位制後反向取值 25 int s[100]; 26 int out=0; 27 int i=0; 28 29 while(d){ 30 s[i]=d%x; 31 d=d/x; 32 ++i; 33 } 34 int q=0; 35 for (int j=i-1;j>=0;--j,++q){ 36 out+=s[j]*pow(x,q); 37 } 38 return out; 39 } 40 int main(){ 41 int n,d; 42 43 while(cin>>n&&n>0){ 44 cin>>d; 45 if (JudgePrime(n)&&JudgePrime(DtoX(n,d))) 46 cout<<"Yes"<<endl; 47 else 48 cout<<"No"<<endl; 49 } 50 }