1015. Reversible Primes 解析

来源:互联网 发布:qq手机骂人软件 编辑:程序博客网 时间:2024/05/23 12:55

题目意思是将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;elsecout << "Yes" << endl;}}return 0;}


0 0
原创粉丝点击