题目描述
因为151既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数。
写一个程序来找出范围[a,b](5 <= a < b <= 100,000,000)( 一亿)间的所有回文质数;
输入格式:
第 1 行: 二个整数 a 和 b .
输出格式:
输出一个回文质数的列表,一行一个。
输入输出样例
输入样例#1: |
|
输出样例#1: |
|
说明
Hint 1: Generate the palindromes and see if they are prime.
提示 1: 找出所有的回文数再判断它们是不是质数(素数).
Hint 2: Generate palindromes by combining digits properly. You might need more than one of the loops like below.
代码:
#include<bits/stdc++.h>
using namespace std;
bool c[100000001];
void prime(int b) {
memset(c, true, sizeof(c));
c[1]=false;
int n=sqrt(b);
for (int i=2;i<=n;i++) {
if (c[i]) {
for (int j=2;j<=b/i;j++)
c[i*j]=false;
}
}
}
bool ishws(int num) {
int temp=num,ans=0;
while (temp!=0) {
ans=ans*10+temp%10;
temp/=10;
}
if (ans==num)
return true;
else
return false;
}
int main() {
int a,b;
cin>>a>>b;
if (b>=10000000)
b=9999999;
prime(b);
if(a>b)
return 0;
for (int i=a;i<=b;i+=2) {
if (c[i] && ishws(i))
cout<<i<<endl;
}
return 0;
}