PAT-1015 Reversible Primes(1不是素数)

版权声明:IT交流QQ群328880248,欢迎大家来一起学习一起交流~本篇文章未经同意请勿转载! https://blog.csdn.net/m0_38072683/article/details/89880968

1015 Reversible Primes (20 分)

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 (<10​5​​) 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

思路

题目比较水,但是第二个点一直没过,参考别人的博客,才突然发现,1不是素数。

代码

#include<cstdio>
#include<cmath>
#include<cstring>

using namespace std;

const int maxn = 1e6 + 100;
int a[maxn],sum;

void solve(int n, int radix){
	memset(a, 0, sizeof(a));
	sum = 0;
	int res = 0;
	int t = n, tem;
	while(t){
		tem = t%radix;
		t /= radix;
		a[sum++] = tem;
	}
	bool flag = false;
	int bei = 1;
	for(int i = sum-1; i >= 0; i--) {
		res += bei*a[i];
		bei *= radix;
	}
	if(res == 1){
		printf("No\n");
		return;
	}
	for(int i = 2; i <= sqrt(res); i++) {
		if(res % i == 0) {
			printf("No\n");
			return;
		}
	}
	printf("Yes\n");
}

int main(){
	int n,d;
	while(~scanf("%d",&n) && n >= 0){
		scanf("%d",&d);
		bool f = false;
		if(n == 1)f = true;
		for(int i = 2; i <= sqrt(n); i++) {
			if(n % i == 0) {
				f = true;
				break;
			}
		}
		if(f){
			printf("No\n");
			continue;
		}
		solve(n,d);	
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_38072683/article/details/89880968
今日推荐