USACO 1.5 Prime Palindromes

1.生成回文数 (100000000以内)大概20000个

2.判断素数

 

生成回文数的算法思想:

分别生成数位是奇odd,和数位是偶even的回文数,

对于串1234, 翻转一下 4321,再接上就生成了一个回文数 ,odd:1234321 even:12344321

实现的方法可以多种多样。我用的是递归的方法。

代码
   
     
1 /*
2 ID: superbi1
3 LANG: C
4 TASK: pprime
5   */
6 #include < stdio.h >
7 #include < math.h >
8 #include < string .h >
9   #define NL 20000
10
11 int plin[NL], npl;
12
13 void genPrim( int high, int low, int val)
14 {
15 int I;
16 if (high < low) {
17 plin[npl ++ ] = val;
18 return ;
19 }
20 if (low == 1 ) I = 1 ;
21 else I = 0 ;
22 for (; I <= 9 ; I ++ ) {
23 if (high == low) genPrim(high - 1 , low + 1 , val + ( int )pow( 10 , high - 1 ) * I);
24 else genPrim(high - 1 , low + 1 , val + ( int )pow( 10 , high - 1 ) * I + ( int )pow( 10 , low - 1 ) * I);
25 }
26 }
27
28 int isPrim( int P)
29 {
30 int M = ( int )sqrt(P);
31 int I;
32 for (I = 2 ; I <= M; I ++ ) {
33 if (P % I == 0 ) return 0 ;
34 }
35 return 1 ;
36 }
37
38 int main()
39 {
40 FILE * fin = fopen( " pprime.in " , " r " );
41 FILE * fout = fopen( " pprime.out " , " w " );
42 int I;
43 int a, b;
44 npl = 0 ;
45 for (I = 1 ; I <= 8 ; I ++ ) {
46 genPrim(I, 1 , 0 );
47 }
48 fscanf(fin, " %d%d " , & a, & b);
49 I = 0 ;
50 while (I < npl) {
51 if (plin[I] >= a) break ;
52 I ++ ;
53 }
54 while (I < npl && plin[I] <= b) {
55 if (isPrim(plin[I])) {
56 fprintf(fout, " %d\n " , plin[I]);
57 }
58 I ++ ;
59 }
60 return 0 ;
61 }

 

你可能感兴趣的:(USACO)