Reversible Primes(题目意思没看懂?快进来看看!)

Reversible Primes

  • 题目
  • 答案
  • 题目含义解析

题目

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 (<10​5​​ ) and D (1

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

答案

#include
#include
#include
using namespace std;

int check(int tmp)
{
     
	if(tmp==1||tmp==0) return 0;
	else if(tmp==2) return 1;
	for(int i=2;i<=sqrt(tmp)+1;i++)
	{
     
		if(tmp%i==0) return 0;
	}
	return 1;
}
int main()
{
     
	while(1)
	{
     
		int num,radix;
		vector<int> vec;
		cin>>num;
		if(num<0) break;
		else cin>>radix;
		int sum1=0,sum2=0;
		while(num!=0)
		{
     
			vec.push_back(num%radix);
			num/=radix;
		}
		for(int i=vec.size()-1;i>=0;i--)
		sum1=sum1*radix+vec[i];
		for(int i=0;i<vec.size();i++)
		sum2=sum2*radix+vec[i];
		int flag1=check(sum1),flag2=check(sum2);
		if(flag1&&flag2) cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	}	
} 

题目含义解析

这道题的意思是将输入的数字转换为对应进制的数,将转换后的结果以及其逆置的结果同时转回10进制,最后判断这两个十进制数是否为素数

还是不明白?我来给大家举个例子,就拿样例中的23 2来说明最后的结果为什么是Yes?

  1. 我们先将23转为2进制,结果为10111
  2. 将10111逆置,得到结果11101
  3. 将10111和11101再转回十进制,得到结果为23和29
  4. 判断23和29是否为素数,很显然两个都是素数
  5. 输出Yes

你可能感兴趣的:(PAT题目练习,PAT)