A1015

本題思路:1、記錄N是否爲素數的判斷(開始遺漏了這處的判斷)
2、將N轉換爲d進制記錄在數組中
3、反轉,實質是數組從下標0處開始遍歷
4、將反轉後的d進制轉換爲十進制
5、對轉換後的十進制判斷是否是素數,同時,結合最開始對N是否爲素數的判斷,只有二者皆爲素數時,該數纔是反轉素數,否則不是.
注意點:1是非素數,需要進行特判

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int store[20];
bool judgePrime(int sample){
	if(sample==1)return false;           //特判1爲非素數 
	int temp=(int)sqrt(1.0*sample);
	for(int i=2;i<=temp;i++){
		if(sample%i==0)return false;
	}
	return true;
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	int n,d;
	bool isPrime=false;                  //記錄該數反轉前是否是素數 
	while(1){
		int j=0,res=0,exp=0;
		scanf("%d",&n);
		if(n<0)break;
		isPrime=judgePrime(n);
		scanf("%d",&d);
		do{
			store[j]=n%d;
			n/=d;
			j++;
		}while(n!=0);
		for(int i=j-1;i>=0;i--){
			int temp=1;
			for(int e=1;e<=exp;e++)temp*=d;
			res+=temp*store[i];
			exp++;
		}
		if(isPrime&&judgePrime(res))printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}

算法筆記中比較好的點:若n本身便是非素數,則輸出No,直接跳過本次循環;通過scanf("%d",&n)!=EOF來結束輸入.

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int store[20];
bool judgePrime(int sample){
	if(sample==1)return false;           //特判1爲非素數 
	int temp=(int)sqrt(1.0*sample);
	for(int i=2;i<=temp;i++){
		if(sample%i==0)return false;
	}
	return true;
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	int n,d;
	while(scanf("%d",&n)!=EOF){
		if(n<0)break;
		int j=0,res=0,exp=0;
		scanf("%d",&d);
		if(!judgePrime(n)){            //判斷反轉前是否是素數,若反轉前不是素數,則無需後續操作,直接輸出No即可 
			printf("No\n");
			continue;
		}                              //注意點:該if條件判斷要寫在輸入d之後,否則在這直接退出本循環,將導致之後的d停滯輸入,放到了下一個循環中 
		do{
			store[j]=n%d;
			n/=d;
			j++;
		}while(n!=0);
		for(int i=j-1;i>=0;i--){
			int temp=1;
			for(int e=1;e<=exp;e++)temp*=d;
			res+=temp*store[i];
			exp++;
		}
		if(judgePrime(res))printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章