1015. Reversible Primes 解析

题目意思是将10进制数转成N进制,在N进制的情况下逆转,然后转换成10进制看是不是素数。

_(:з)∠)_计算机对素数是真爱啊!!!!


#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

struct Node {
	int Num;
	int Radix;
};


char int2char(int i) {
	char c;
	switch (i)
	{
	case 0:c = '0'; break;
	case 1:c = '1'; break;
	case 2:c = '2'; break;
	case 3:c = '3'; break;
	case 4:c = '4'; break;
	case 5:c = '5'; break;
	case 6:c = '6'; break;
	case 7:c = '7'; break;
	case 8:c = '8'; break;
	case 9:c = '9'; break;
	default:
		break;
	}
	return c;
}

int char2int(char c) {
	return int(c) - int('0');
}


string dec2N(int i,int N) { //十进制转N进制
	int temp = i;
	int len = 0;
	int digit = 0;

	while (temp) {
		len++;
		temp = temp / N;
	}
	char * t = new char[len + 1];

	temp = i;
	int j;
	for ( j= 0; j < len; j++) {
		t[j] = int2char(temp % N);
		temp /= N;
	}
	t[j] = '\0';
	
//	cout << "len :" << strlen(t) << endl;
	string s = t;
	return s;

}

int N2dec(string str, int N) { //N进制转十进制
	int sum = 0;
	for (int i = 0; i < str.size(); i++) {
		sum *= N;
		sum += char2int(str[i]);
//		cout << str[i] << " " << sum << endl;
	}
	return sum;
}


bool isPrimes(int num) {
	if (num <= 1)
		return false;
	for (int i = 2; i * i <=  num; i++) {
		if (num % i == 0) return false;
	}
	return true;
}

int main() {
	vector <Node> List;
	Node temp;

	cin >> temp.Num;
	while (temp.Num >= 0 ) {
		cin >> temp.Radix;
		List.push_back(temp);
		cin >> temp.Num;
	}
	
	
	for (int i = 0; i < List.size(); i++) {
		if (!isPrimes(List[i].Num))
			cout << "No" << endl;
		else {
			string temps = dec2N(List[i].Num, List[i].Radix);
			int decs = N2dec(temps, List[i].Radix);
//			cout << List[i].Num << " " << decs << endl;
			if (!isPrimes(decs))
				cout << "No" << endl;
			else
				cout << "Yes" << endl;
		}
	}
	

	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>