EASY_PAT_ZJU_ADVANCED LEVEL 1015 進制轉換 素數

1015. Reversible Primes (20)

時間限制
400 ms
內存限制
32000 kB
代碼長度限制
16000 B
判題程序
Standard
作者
CHEN, Yue

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.

Sample Input:
73 10
23 2
23 10
-2
Sample Output:
Yes
Yes
No

/************************************************
	@ AUTHOR	: GAOMINQUAN
	@ DATA		: 2014 - 2 - 24
	@ MAIL		: [email protected]
	@ HARD		: EASY **

/************************************************/

#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

vector<int> change_radix(int num,int R){
	vector<int> newNum;
	if(num == 0)
		newNum.push_back(0);
	else{
		while(num>0){
			newNum.push_back(num%R);
			num /= R;
		}
	}
	return newNum;
}
int merge_vec_to_reverse_num(vector<int> numbers,int radix){ // cheng vector<int> to reversed real number
	int answer = 0;
	int exp = 0;
	for(int numI = numbers.size()-1; numI>=0; numI--){
		answer += numbers[numI] * pow(radix,exp++);
	}// 利用位數相除的方式,pushBack的數字本來就是反着的,就是說,num[0]是最低位“0",而不是100000中的“1”
	 /*
	 所以說,如果要計算其原本等於多少,就應該從最低位*pow(R,0++)一直這樣下去,所以,如果求逆轉,就要從最高位開始。最高的NUM*pow(R,0++)
	*/
	return answer;
}

bool is_primer(int num){
	int isPrimer = true;
	if(num == 0 || num == 1){
		isPrimer = false;
	}else{
		for(int i = 2; i<=sqrt(num); i++){ //NOTICE HERE!!!!!!!!!!!!!!!!!!!!
			if( num % i == 0){
				isPrimer = false;
				break;
			}
		}
	}
	
	return isPrimer;
}

int main(){
	int num = 23, radix = 2;
	while(true){
		cin>>num;
		if(num<0){
			break;
		}else{
			cin>>radix;
			vector<int> test = change_radix(num,radix);
			if(is_primer((merge_vec_to_reverse_num(test,radix))) && is_primer(num)){
				cout<<"Yes"<<endl;
			}else{
				cout<<"No"<<endl;
			}
		}
	}
	return 0;
	
}


發佈了40 篇原創文章 · 獲贊 3 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章