UVA10235 Simply Emirp 的题解
UVA传送门
题目大意
如果一个质数(prime),它翻转后还是质数(翻转就是 1234 → 4321 1234→4321 1234→4321),则把它称为(emirp)
给你一个整数 n n n,判断它是否有以下的性质:
-
如果不是素数,就输出
n is not prime.
。 -
如果是素数但反转后的数不是素数,就输出
n is prime.
。 -
如果是反转后的数还是素数,就输出
n is emirp.
。
思路
因为数据范围较大 1 < n < 1000000 1<n<1000000 1<n<1000000,所以不能使用暴力筛法。这里我用的是埃氏筛。
首先用埃氏筛判断这个数是否是素数,然后将这个数翻转,判断这个数反转后是否为素数。
注意:像 2 2 2, 3 3 3, 5 5 5, 7 7 7, 11 11 11,只属于素数。
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <climits>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <ctime>
#include <string>
#include <cstring>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int n;
bool vis[1000005];
signed main() {
vis[0] = 0;
vis[1] = 1;
for (int i = 2; i <= 1000000; i ++) {
if (vis[i]) {
continue;
}
for (int j = i * i; j <= 1000000; j += i) {
vis[j] = 1;
}
}
while (cin >> n) {
if (vis[n]) {
cout << n << " is not prime.\n";
}
else {
int x = n;
int m = 0;
while (x) {
m *= 10;
m += x % 10;
x /= 10;
}
if (!vis[m] && n != m) {
cout << n << " is emirp.\n";
}
else {
cout << n << " is prime.\n";
}
}
}
return 0;
}
其实也可以用线性筛
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <climits>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <ctime>
#include <string>
#include <cstring>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int p[100005],t;
bool q[1000005];
void P(int u) {//线性筛
q[0]=q[1]=1;
for(int i=1;i<=u;i++) {
if(!q[i])p[++t]=i;
for(int j=1;j<=t&&i*p[j]<=u;j++) {
q[i*p[j]]=1;
if(!(i%p[j]))break;
}
}
}
int K(int u)//翻转
{
int x=u,s=0;
while(x)s*=10,s+=x%10,x/=10;
return s;
}
int main() {
int n;
P(1000000);
while(scanf("%d",&n)!=EOF) {
if(q[n])printf("%d is not prime.",n);
else if(!q[K(n)]&&n!=K(n))printf("%d is emirp.",n);
else printf("%d is prime.",n);
puts("");
}
return 0;
}