Palindromic Squares
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:10239512
3 PROG:palsquare
4 LANG:C++
5 */
6
7 #include<iostream>
8 #include<cstring>
9 #include<fstream>
10 //#define fout cout
11 //#define fin cin
12 using namespace std;
13 ifstream fin("palsquare.in");
14 ofstream fout("palsquare.out");
15
16 int a[100],b[100]={0};
17 int c;
18
19 bool dfs(int k){
20 int i;
21 for(i=1;i<=k/2;i++)
22 if(a[i]!=a[k-i+1])
23 return 0;
24 return 1;
25 }
26
27 void print(int c){
28 if(c<10) {fout<<c;return ;}
29 switch(c)
30 {
31 case 10: fout<<'A';break;
32 case 11: fout<<'B';break;
33 case 12: fout<<'C';break;
34 case 13: fout<<'D';break;
35 case 14: fout<<'E';break;
36 case 15: fout<<'F';break;
37 case 16: fout<<'G';break;
38 case 17: fout<<'H';break;
39 case 18: fout<<'I';break;
40 case 19: fout<<'A';break;
41 }
42
43 }
44
45 int main()
46 {
47 fin>>c;
48 int i,j,k,l;
49 for(i=1;i<=300;i++)
50 {
51 j=i*i;
52 k=1;
53 while(j>0)
54 {
55 a[k]=j%c;
56 k++;
57 j=j/c;
58 }
59 if(dfs(k-1))
60 {
61 j=1;
62 l=i;
63 while(l>0)
64 {
65 b[j]=l%c;
66 j++;
67 l=l/c;
68 }
69 j--;
70 while(j>=1)
71 {
72 print(b[j]);
73 j--;
74 }
75 fout<<" ";
76 k--;
77 while(k>=1)
78 {
79 print(a[k]);
80 k--;
81 }
82 fout<<endl;
83
84 }
85 //system("pause");
86 }
87 return 0;
88
89 }
90