PAT 1015. Reversible Primes

PAT 1015. 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 (< 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

分析

先判断数是否是prime,然后化为radix进制,再反转,再化成十进制判断是不是prime;看了半天才明白什么意思

代码如下

#include<iostream>
#include<math.h>
using namespace std;
long long int toradix(long long n,long long int radix){
	string num;
	while(n!=0){
		num.insert(num.begin(),1,'0'+n%radix);
		n/=radix;
	}
	return stoll(num);
}
bool isprime(long long int num){
	if(num<=1) return false;
	for(int i=2;i<=sqrt(num);i++)
	if(num%i==0) return false;
	return true;
}
long long int toten(string n,long long int radix){
	long long int m=0,tag=0;
	for(int i=n.size()-1;i>=0;i--)
	m+=pow(radix,tag++)*(n[i]-'0');
	return m;
}
int main(){
	long long int radix,num,n;
	while(1){
	int flag=1; string m,s;
	cin>>n;
	if(n<0) return 0;
	cin>>radix;
	if(!isprime(n)) flag=0; 
	n=toradix(n,radix); 
	s=to_string(n);
	for(int i=s.size()-1;i>=0;i--)
	m.append(1,s[i]); 
	n=toten(m,radix);
	if(!isprime(n)) flag=0;
	flag>0?cout<<"Yes"<<endl:cout<<"No"<<endl;
	}
	return 0;
} 
原文地址:https://www.cnblogs.com/A-Little-Nut/p/8207060.html