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.


IDEA

1.A reversible prime in any number system is a prime whose "reverse" in that number system is also a prime。

翻译:首先这个数必须是素数。然后将这个数(1)转为D进制数(2),再将这个D进制数反转(3)将反转后的数再转为十进制数,这个十进制数依然是素数。

2.判断是否是素数1015. Reversible Primes (20)_第1张图片

a==0,a==1是非素数,判断<=sqrt(a)

CODE

#include<iostream>
#include<cmath>
using namespace std;
int isPrime(long long a){
	if(a==0||a==1){
		return 0;
	}
	for(long long i=2;i<=sqrt(a);i++){
		if(a%i==0){
			return 0;
		}
	}
	return 1;
}

int main(){
	int n,d;
	while(cin>>n&&n>=0){
		cin>>d;
		if(!isPrime(n)){
			cout<<"No"<<endl;
			continue;
		}
		long long tmp[100000],i=0;
		while(n){
			tmp[i++]=n%d;
			n/=d;
		}
		long long m=1,sum=0;
		for(int j=i-1;j>=0;j--){
			sum+=tmp[j]*m;
			m*=d;
		}
		if(!isPrime(sum)){
			cout<<"No"<<endl;
		}else{
			cout<<"Yes"<<endl;
		}
	}
	return 0;
}


你可能感兴趣的:(pat,判断素数,其他进制与十进制转换)