PAT 1015 Reversible Primes (20)

1015 Reversible Primes (20)(20 分)

A 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

思路:

首先用素数筛筛出素数,然后原数判断一次,利用栈把原数倒一下,倒过来的数再判断一次。

扫描二维码关注公众号,回复: 2674367 查看本文章

代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>  
#include <set>
using namespace std;

#define MAX 100000
int su[MAX], cnt;
bool isprime[MAX];
stack<int> s;

void prime()
{
	memset(isprime, true, sizeof(isprime));
	isprime[0] = isprime[1] = false;
	cnt = 1;
	for (int i = 2; i<MAX; i++)
	{
		if (isprime[i])
			su[cnt++] = i;
		for (int j = 1; j < cnt&&su[j] * i < MAX; j++)
			isprime[su[j] * i] = false;
	}
}

int main()
{
	prime();
	int n, d;
	while (cin >> n && n >= 0)
	{
		cin >> d;
		if (isprime[n])
		{
			while (n)
			{
				s.push(n%d);
				n /= d;
			}
			int mul = 1;
			while (!s.empty())
			{
				n += mul * s.top();
				s.pop();
				mul *= d;
			}
			if (isprime[n])
			{
				cout << "Yes" << endl;
				continue;
			}
		}
		cout << "No" << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ryo_218/article/details/81545219
今日推荐