Day42: [PAT甲级] 1015 Reversible Primes (20分)

Day42: [PAT甲级] 1015 Reversible Primes (20分)

题源:

来自PAT甲级题库:

https://pintia.cn/problem-sets/994805342720868352/problems/994805495863296000

代码:

dirty code凑合看吧
三种函数要熟练:其他进制转10进制;10进制转其他进制;判断素数

#include<iostream>
#include<string>
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
int N, D;
string ten_D_re(int N, int D);
long long D_ten_re(string N, int D);
bool isprime(long long X);
int main() {
	while (cin >> N)
	{
		if (N < 0)break;
		cin >> D;
		//cout << "!" << N << " " << D << endl;
		if (!isprime(N)) {
			cout << "No" << endl;
			continue;
		}
		string x = ten_D_re(N, D);
		if (isprime(D_ten_re(x, D))) {
			cout << "Yes" << endl;
		}
		else {
			cout << "No" << endl;
		}

	}
	system("pause");
}
string ten_D_re(int N, int D) {//10进制转n进制
	if (N == 0) return "0";
	string ans;
	while (N) {
		//cout << "@" << N << endl;
		int temp = N % D;
		//cout <<"!"<<temp<<endl ;
		if (temp < 10) {
			ans.append(1, '0' + temp);
		}
		else {
			ans.append( 1, 'A' + temp - 10);
		}
		N = N / D;
	}
	return ans;
}
long long D_ten_re(string N, int D) {//n进制转10进制
	long long sum = 0;
	int j = 1;
	for (int i=N.size()-1;i>=0;i--) {
		int x = N[i] - '0';
		sum += x * j;
		j = j * D;
	}
	return sum;
}
bool isprime(long long X) {
	if (X <= 1) return false;
	if (X == 2 || X == 3) return true;
	for (int i = 2;i*i<=X;i++) {
		if (X%i == 0) return false;
	}
	return true;
}
发布了49 篇原创文章 · 获赞 13 · 访问量 503

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103914531