PAT A 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

 

题目没讲明白,实际给的数是10进制的,

需要转换到相应的进制下,然后求“reverse”,考虑是不是两者都是质数。

 

代码:

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

//题目给的数是10进制的,要转换为d进制后求reverse

int To_num(string n,int d);	//将字符串表示的数转换为10进制数
int Reverse(int num,int d);	//求reverse后的数的10进制表示
bool Is_prime(int n);	//求是否为素数

int main()
{
	string n;
	int d,num1,num2;

	while(cin>>num1)
	{
		if(num1<0)
			break;
		else
			cin>>d;
		num2=Reverse(num1,d);		
		if(Is_prime(num1)&&Is_prime(num2))
			cout<<"Yes\n";
		else
			cout<<"No\n";
	}

	return 0;
}

int To_num(string n,int d)	//将字符串表示的数转换为10进制数
{
	int num=0,i;
	if(n[0]=='-')
		return -1;
	for(i=0;i<n.size();i++)
		num=num*d+n[i]-'0';
	return num;
}

int Reverse(int num,int d)	//求reverse后的数的10进制表示
{
	int i;
	string n;
	if(num==0)
		return 0;
	while(num>0)
	{
		n+=num%d+'0';
		num/=d;
	}
	return To_num(n,d);
}

bool Is_prime(int n)	//求是否为素数
{
	int sq=sqrt((double)n);
	int i;
	if(n==0||n==1)
		return false;
	for(i=2;i<=sq;i++)
	{
		if(n%i==0)
			return false;
	}
	return true;
}


 

 

 

你可能感兴趣的:(C++,pat)