题目描述
因为 151 既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数。
写一个程序来找出范围 [a,b] (5≤a<b≤100,000,000)( 一亿)间的所有回文质数。
输入格式
第 1 行: 二个整数 a 和 b .
输出格式
输出一个回文质数的列表,一行一个。
输入输出样例
| 输入#1 | 输出#1 |
|---|---|
| 5 500 | 5 |
| 7 | |
| 11 | |
| 101 | |
| 131 | |
| 151 | |
| 181 | |
| 191 | |
| 313 | |
| 353 | |
| 373 | |
| 383 |
思路: 输入的区间可能很大,按照常规的枚举一定会T掉的,所以这道题直接循环构造出回文串,然后再判断它是不是质数(数的的尾数一定不是奇数,决定尾数的循环+=2可以减少一些不必要的循环)的方式,然后可以ac这题。
代码如下:
#include <iostream>
#include <cmath>
using namespace std;
int judge(int x)
{
int i;
if(x==1)
return 0;
for(i=2;i<=sqrt(x);i++)
{
if(x%i==0)
return 0;
}
return 1;
}
int main()
{
int d1,d2,d3,d4,d5,shu,l,r;
cin>>l>>r;
if(l<=10)
for(d1=1;d1<=9;d1++)
{
shu=d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
if(l<=100)
for(d1=1;d1<=9;d1+=2)
{
shu=d1*10+d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
if(l<=1000)
for(d1=1;d1<=9;d1+=2)
{
for(d2=0;d2<=9;d2++)
{
shu=d1*100+d2*10+d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
}
if(l<=10000)
for(d1=1;d1<=9;d1+=2)
{
for(d2=0;d2<=9;d2++)
{
shu=d1*1000+d2*100+d2*10+d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
}
if(l<=100000)
for(d1=1;d1<=9;d1+=2)
{
for(d2=0;d2<=9;d2++)
{
for(d3=0;d3<=9;d3++)
{
shu=d1*10000+d2*1000+d3*100+d2*10+d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
}
}
if(l<=1000000)
for(d1=1;d1<=9;d1+=2)
{
for(d2=0;d2<=9;d2++)
{
for(d3=0;d3<=9;d3++)
{
shu=d1*100000+d2*10000+d3*1000+d3*100+d2*10+d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
}
}
if(l<=10000000)
for(d1=1;d1<=9;d1+=2)
{
for(d2=0;d2<=9;d2++)
{
for(d3=0;d3<=9;d3++)
{
for(d4=0;d4<=9;d4++)
{
shu=d1*1000000+d2*100000+d3*10000+d4*1000+d3*100+d2*10+d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
}
}
}
if(l<=100000000)
for(d1=1;d1<=9;d1+=2)
{
for(d2=0;d2<=9;d2++)
{
for(d3=0;d3<=9;d3++)
{
for(d4=0;d4<=9;d4++)
{
shu=d1*10000000+d2*1000000+d3*100000+d4*10000+d4*1000+d3*100+d2*10+d1;
if(shu>r)
break;
if(shu<l)
continue;
if(judge(shu))
cout<<shu<<endl;
}
}
}
}
return 0;
}
本文介绍了一种高效的算法,用于在给定区间(5到1亿)内查找回文质数,通过构建回文数并利用质数判断技巧,避免了常规枚举的大量计算,展示了针对大规模数据的优化策略。
287

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



