一开始用常规的方法判断素数,结果超时很严重,后来查到了筛选法求素数这个,效率高了很多,同时因为输出比较多,最好用printf,减少时间
#include <bits/stdc++.h>
#include <cstdio>
#define max 10000005
using namespace std;
int arr[max];
bool noprime[max];
int cot=0;
bool rev(int n){
int a=n,b=0;
while(a!=0){
b=b*10+a%10;
a /= 10;
}
if(b==n) return true;
else return false;
}
//筛选法求素数,把所有素数标为false
void check(){
memset(noprime,false,sizeof(noprime));
noprime[0]=noprime[1]=true;
for(int i=2; i<=sqrt(max); i++ )
{ if(!noprime[i])
for(int j=i*i; j<=max; j+=i ) noprime[j]=true;
}
for(int i=5; i <= max; i++){
if(rev(i)==true&&noprime[i]==false){
arr[cot++]=i;
}
}
}
int main()
{
check();
int l,r;
while(scanf("%d%d",&l,&r)){
if(l==0&&r==0) break;
else{
int i=0;
while(arr[i] < l){
i++;
}
while (arr[i] <= r && arr[i] != 0)
{
printf ("%d\n",arr[i]);
i++;
}
}
}
}
本文介绍了一种使用筛选法高效找出特定范围内的回文素数的方法,并通过实例演示了如何利用C++实现该算法。针对大量输出的需求,文章还推荐使用printf以减少运行时间。
701

被折叠的 条评论
为什么被折叠?



