USACO1.2.4--Palindromic Squares

Palindromic Squares
Rob Kolstad

Palindromes are numbers that read the same forwards as backwards. The number 12321 is a typical palindrome.

Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on.

Print both the number and its square in base B.

PROGRAM NAME: palsquare

INPUT FORMAT

A single line with B, the base (specified in base 10).

SAMPLE INPUT (file palsquare.in)

10

OUTPUT FORMAT

Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself.

SAMPLE OUTPUT (file palsquare.out)

1 1
2 4
3 9
11 121
22 484
26 676
101 10201
111 12321
121 14641
202 40804
212 44944
264 69696

 题解:还是纯模拟,先转进制,再判断是否是回文。

View Code
 1 /*
 2 ID:spcjv51
 3 PROG:palsquare
 4 LANG:C
 5 */
 6 #include<stdio.h>
 7 #include<string.h>
 8 int a[50],b[50];
 9 char s[20]= {"0123456789ABCDEFGHIJ"};
10 int bb,len1,len2;
11 void conversion(int i)
12 {
13     int m,len;
14     m=i*i;
15     len1=0;
16     while(i)
17     {
18         len1++;
19         a[len1]=i%bb;
20         i/=bb;
21     }
22     len2=0;
23     while(m)
24     {
25         len2++;
26         b[len2]=m%bb;
27         m/=bb;
28     }
29 }
30 
31 int findd(void)
32 {
33     int i,l;
34     l=len2/2;
35     for(i=1; i<=l; i++)
36         if(b[i]!=b[len2-i+1]) return 0;
37     return 1;
38 
39 }
40 int main(void)
41 {
42     FILE *fin=fopen("palsquare.in","r");
43     FILE *fout=fopen("palsquare.out","w");
44     long i,n,j;
45     fscanf(fin,"%d",&bb);
46     for(i=1; i<=300; i++)
47     {
48         conversion(i);
49         if(findd())
50         {
51             for(j=len1;j>=1;j--) fprintf(fout,"%c",s[a[j]]);
52             fprintf(fout," ");
53             for(j=1;j<=len2;j++) fprintf(fout,"%c",s[b[j]]);
54             fprintf(fout,"\n");
55         }
56 
57     }
58     fclose(fin);
59     fclose(fout);
60     return 0;
61 }

 

posted on 2013-01-08 22:34  仗剑奔走天涯  阅读(216)  评论(0编辑  收藏  举报

导航