1015 Reversible Primes (20 分)

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 (<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

代码

注意PAT中不能使用 itoa() 函数进行进制转换,除此之外还有gets函数也不能使用

itoa的用法

#include

using namespace std;

const int maxn = 100005;

bool isPrime[maxn];
//vector prime; // 存储素数的数组,此题不用 

// 初始化是否是素数的数组 
void init() {
     
	fill(isPrime,isPrime+maxn,true);
	for(int i=2; i<maxn; i++) {
     
		if(isPrime[i]) {
     
			// prime.push_back(i); // 将素数存出来,此题用不到 
			for(int j=i+i; j<maxn; j+=i) {
     
				isPrime[j] = false;
			}
		}
	}
	isPrime[1] = false;
}

int revers(int num, int base){
     
	int n=0,sum=0;
	int buffer[maxn];
	while(num){
     
		buffer[n++] = num%base;
		num /= base;
	}
	for(int i=n-1; i>=0; i--){
     
        sum += buffer[i]*pow(base,n-i-1);
    }
    return sum;
}

int main(){
     
	init();
	int v,n;
	
	while(cin >> v) {
     
		if(v < 0) {
     
			break;
		}
		cin >> n;
		int num = revers(v,n);
		if(isPrime[v] && isPrime[num]) {
     
			cout << "Yes" << endl;
		} else {
     
			cout << "No" << endl;
		}
	}
	return 0;
}

你可能感兴趣的:(#,PAT,算法练习,PAT)