回文质数
题目描述
因为151既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数。
写一个程序来找出范围[a,b](5 <= a < b <= 100,000,000)( 一亿)间的所有回文质数;
分析:这题直接枚举会超时,我们知道质数不可能是偶数,所以枚举的时候可以直接i+2,这样就可以少枚举一半的数,然后一定要先判断回文数再判断质数,判断质数要花更多时间,但是如果用普通判断还是会超时,数据范围是100000000,其实只要枚举到9989899(一亿内最大质数)就可以了。
代码
var
i,l,r:longint;
function check(x:longint):boolean;
var
i,j:longint;
s:string;
begin
check:=true;
str(x,s);
i:=1;j:=length(s);
while i<=j do
begin
if s[i]<>s[j] then exit(false);
inc(i);dec(j);
end;
for i:=2 to trunc(sqrt(x)) do
if x mod i=0 then exit(false);
end;
begin
readln(l,r);
i:=l;
if r>9989899 then r:=9989899;
if not odd(i) then inc(i);
while i<=r do
begin
if check(i) then writeln(i);
inc(i,2);
end;
end.