usaco 1.5.2——pprime
Prime Palindromes 回文质数
描述
因为151即是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 号是回文质数。
写一个程序来找出范围[a,b](5 <= a < b <= 100,000,000)间的所有回文质数;
格式
PROGRAM NAME: pprime
INPUT FORMAT:
(file pprime.in)
第 1 行: 二个整数 a 和 b .
OUTPUT FORMAT:
(file pprime.out)
输出一个回文质数的列表,一行一个。
SAMPLE INPUT
5 500
SAMPLE OUTPUT
5
7
11
101
131
151
181
191
313
353
373
383
Compiling...
Compile: OK
Executing...
Test 1: TEST OK [0.027 secs, 4180 KB]
Test 2: TEST OK [0.027 secs, 4180 KB]
Test 3: TEST OK [0.027 secs, 4180 KB]
Test 4: TEST OK [0.027 secs, 4180 KB]
Test 5: TEST OK [0.027 secs, 4180 KB]
Test 6: TEST OK [0.027 secs, 4180 KB]
Test 7: TEST OK [0.027 secs, 4180 KB]
Test 8: TEST OK [0.027 secs, 4180 KB]
Test 9: TEST OK [0.027 secs, 4180 KB]
All tests OK.
Your program ('pprime') produced all correct answers! This is your submission #2 for this
problem. Congratulations!
本来暴力枚举的,没过,
在参考HINT后
我打了个更暴力的暴力枚举,
过了。。。。。。
看代码,不解释。
{ ID: codeway3 PROG: pprime LANG: PASCAL } program pprime; var i,j,n,m,k,l,r:longint; a1,a2,a3,a4:longint; a:array[1..1000000]of longint; function pd(x:longint):boolean; var s:string; le,i:longint; begin for i:=2 to trunc(sqrt(x)) do if x mod i=0 then exit(false); if (x<l)or(x>r) then exit(false); exit(true); end; procedure sort(l,r:longint); var i,j,x,y:longint; begin i:=l;j:=r; x:=a[(l+r)div 2]; repeat while a[i]<x do inc(i); while a[j]>x do dec(j); if i<=j then begin y:=a[i];a[i]:=a[j];a[j]:=y; inc(i);dec(j); end; until i>j; if i<r then sort(i,r); if l<j then sort(l,j); end; begin assign(input,'pprime.in'); reset(input); assign(output,'pprime.out'); rewrite(output); readln(l,r); for a1:=1 to 9 do begin k:=a1;if pd(k) then begin inc(n);a[n]:=k;end; k:=a1*10+a1;if pd(k) then begin inc(n);a[n]:=k;end; end; for a1:=1 to 9 do for a2:=0 to 9 do begin k:=a1*100+a2*10+a1;if pd(k) then begin inc(n);a[n]:=k;end; k:=a1*1000+a2*100+a2*10+a1;if pd(k) then begin inc(n);a[n]:=k;end; end; for a1:=1 to 9 do for a2:=0 to 9 do for a3:=0 to 9 do begin k:=a1*10000+a2*1000+a3*100+a2*10+a1;if pd(k) then begin inc(n);a[n]:=k;end; k:=a1*100000+a2*10000+a3*1000+a3*100+a2*10+a1;if pd(k) then begin inc(n);a[n]:=k;end; end; for a1:=1 to 9 do for a2:=0 to 9 do for a3:=0 to 9 do for a4:=0 to 9 do begin k:=a1*1000000+a2*100000+a3*10000+a4*1000+a3*100+a2*10+a1; if pd(k) then begin inc(n);a[n]:=k;end; k:=a1*10000000+a2*1000000+a3*100000+a4*10000+a4*1000+a3*100+a2*10+a1; if pd(k) then begin inc(n);a[n]:=k;end; end; sort(1,n); for i:=1 to n do writeln(a[i]); close(input); close(output); end.