93人阅读 评论(0)

# 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、再写一个函数判断是否为素数即可审题10min+编码20min+调试5min是我预计能做出来的时间，结果，在是否为素数的地方，n小于2时，写了个抛出异常，自己把自己往火坑里推啊，这里其实直接返回FALSE就可以了。【题目总结】进制转换，素数的判断//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;
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：53163次
• 积分：1394
• 等级：
• 排名：千里之外
• 原创：77篇
• 转载：84篇
• 译文：0篇
• 评论：4条
阅读排行
最新评论