# 1015. Reversible Primes (20)

400 ms

65536 kB

16000 B

Standard

CHEN, Yue

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、一开始输入的数是10进制的，与后面跟的进制D的值无关；

2、写一个函数，将10进制的数按照D的值转化成相应的进制，并翻转，再转化为十进制的数；

3、再写一个函数判断是否为素数即可

【题目总结】进制转换，素数的判断

//1015. Reversible Primes (20)http://www.patest.cn/contests/pat-a-practise/1015
struct Num
{
int n;
int d;
};

int GetReversible(int n, int d)//函数实现将10进制数，按D进制的数n实现翻转，并返回一个10进制的数
{
vector<int> revers_num;
int shang = n / d;
int yushu = n%d;
revers_num.push_back(yushu);
while (shang != 0)
{
yushu = shang%d;
shang = shang / d;
revers_num.push_back(yushu);
}

int rnum = 0;
int size = revers_num.size();

for (int i = 0; i < size; i++)
{
int coeff = revers_num[i];
rnum += coeff*pow(d, size - 1 - i);
}

return rnum;
}

inline bool IsPrimes(int n)//判断一个数是否为素数
{
if (n < 2)
return false;//这里要注意，原来我写的是抛出异常，其实不必，直接返回FALSE就可以了
//当时这里写的throw 0，导致程序一致有一个测试用例过不了，耽误了时间
else if (n == 2)
{
return true;
}
else
{
for (int i = 2; i <= sqrt(n);i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
}

int main()
{
int n;
vector<Num> nums;
while (cin>>n)
{
if (n < 0)
{
break;
}
else
{
Num num;
num.n = n;
cin >> num.d;
nums.push_back(num);
}
}

for (int i = 0; i < nums.size(); i++)
{
Num num;
num.n = nums[i].n;
num.d = nums[i].d;
if (IsPrimes(num.n))//如果n是素数
{
int reversNum = GetReversible(num.n, num.d);//求它的反，并判断其是否也为素数
if (IsPrimes(reversNum))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
}
else
{
cout << "No" << endl;
}
}

return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：1015. Reversible Primes (20) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)