1015 Reversible Primes (20分)
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
First, the item analysis:
Input decimal numbers hexadecimal N & D, if N is a prime number & D according to the number after the decimal conversion is a prime number, otherwise, outputs the output Yes No.
Second, the problem-solving ideas:
- It determines whether the prime number N (N is a prime number can perform the next operation)
- The N D from decimal to binary conversion & num1 be bitwise inverted num2
- Num2 The conversion from binary to decimal number result D
- Determining whether the result is a prime number
Points to note:
- Prime decision:
- 1 is neither bonded nor prime number (to be determined individually, or go through the test point 2)
- The cycling conditions for beginners for (int i = 2; i <= (int) sqrt (num1 * 1.0); i ++)
- Decimal conversion:
- Decimal -> D Hex: In accordance with the principle of the conversion formula (do not repeat them here)
- D Hex -> Decimal: take over the storage cycle of the output array
- This problem not only to binary conversion, the conversion take several bit inversion: can cycle modulo modulo operation simplified procedures / memory array to facilitate the calculation
#include <iostream>
#include <math.h>
using namespace std;
int convert(int num1,int radix){
//直接转化为对应的进制数,并实现了数位反转
int num2=0;
int k=0;
int result=0;
while(num1/radix){
num2=num2*10+num1%radix;
num1/=radix;
k++;
}
num2=num2*10+num1;
k++;
//反转后的进制数转化回十进制数
for(int i=0;i<k;i++){
result+=(num2%10)*pow(radix,i);
num2/=10;
}
return result;
}
bool isprime(int num1){ //素数的判断
if(num1==1) //1不是素数也不是合数,要单独判断(否则测试点2过不去)
return false;
for(int i=2;i<=(int)sqrt(num1*1.0);i++){
if(num1%i==0)
return false;
}
return true;
}
int main()
{
int num1; //十进制数
int num2; //转化后的数
int radix; //基数、进制数
cin>>num1;
while(num1>=0){
cin>>radix;
if(!isprime(num1))
cout<<"No"<<endl;
else {
num2=convert(num1,radix);
//cout<<"num2:"<<num2<<endl;
if(isprime(num2))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
cin>>num1;
}
return 0;
}