P2667 超级质数

https://www.luogu.org/problem/show?pid=2667

题目背景

背景就是描述,描述就是背景。。。。。。

题目描述

一个质数如果从个位开始,依次去掉一位数字,两位数字,三位数字。。。。。。直到只剩一位数字中间所有剩下的数都是质数,则称该质数为一个超级质数。例如:2333是一个质数,因为2333,233,23,2都是质数,所以2333是一个四位超级素数。请你写一个程序,给定一个整数X,求大小小于X的超级质数。

输入输出格式

输入格式:

一行,给出一个整数X(1<=X<=100000000).

输出格式:

第一行,一个整数k,表示X以内超级质数的个数.

第2至k+1行,每行一个整数,输出所有X以内的超级质数,这些数按从小到大的顺序排列。

输入输出样例

输入样例#1:
100
输出样例#1:
13
2
3
5
7
23
29
31
37
53
59
71
73
79

说明

对于30%的数据,X<=1000。

对于100%的数据,X<=100000000。

本想线性筛预处理的,但是X太大了。

再想一想,素数本就很少,在超级质数这个苛刻条件下,就根是少得可怜。

所以我们就想,一个超级质数,必定以A(2,3,5,7)开头,以B(1,3,5,7)结尾。

每次加入B中一个数,那么复杂度是O(8^4)

#include<iostream>
#include<cstdio>
#include<math.h>
#include<algorithm>
#include<queue>
#include<string.h>
using namespace std;
#define LL long long 
LL X;
int ans,b[90];
int then[6]={0,1,3,7,9};
bool check(LL x)
{
    if(x==1)    return 0;
    for(int i=2;i<=sqrt(x);i++)
        if(x%i==0)    return 0;
    return 1;
} 
void dfs(LL tot)
{
    if(tot>=X)    return;    
    b[++ans]=tot;
    for(int i=1;i<=4;i++)
    if(check(tot*10+then[i]))    
        dfs(tot*10+then[i]);
}
int main()
{
    cin>>X;    
    dfs(2);dfs(3);dfs(5);dfs(7);
    sort(b+1,b+1+ans);
    cout<<ans<<endl;
    for(LL i=1;i<=ans;i++)
        printf("%d
",b[i]);
    return 0;
} 
原文地址:https://www.cnblogs.com/CLGYPYJ/p/7326337.html