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
一、试题分析:
输入十进制数N & 进制数D,如果N为素数 & 按照进制D转化后的数也是素数,则输出Yes否则输出No。
二、解题思路:
- 判断N是否为素数(N为素数才可以进行接下来的工作)
- 将N从十进制num1转化为D进制 & 将其按位反转为num2
- 将num2从D进制数转化为十进制result
- 判断result是否为素数
注意要点:
- 素数判断:
- 1既不是质数也不是合数(要单独判断,否则测试点2过不去)
- 循环条件初学者使用for(int i=2;i<=(int)sqrt(num1*1.0);i++)
- 进制的转化:
- 十进制 -> D进制:按照公式原理转化(此处不赘述)
- D进制 -> 十进制:每次取余存到数组循环输出
- 本题中不仅要进制转化,转化后还需要数位反转:可以循环进行取余取模操作简化步骤 / 存到数组中便于计算
#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;
}
Ariel_x 发布了28 篇原创文章 · 获赞 2 · 访问量 6548 私信 关注