USACO 1.2 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

这道题目还是用枚举做,要注意的是转化成n进制的时候  n>10 的情况
View Code
 1 /*
 2 ID: shuyang1
 3 PROG: palsquare
 4 LANG: C++
 5 */
 6 #include <iostream>
 7 #include <stdio.h>
 8 #include <string>
 9 using namespace std;
10 
11 int n;   //n表示进制数;
12 char buf[100];   //存放n进制数;
13 
14 void change(int m,int r)   //m为十进制数,r为进制数
15 {
16     char buff[100];
17     int p,q,i,j;
18     if(r<=10)
19     {
20         j=0;
21         while(m!=0)
22         {
23             p=m%r;
24             m=m/r;
25             buff[j]=p+'0';
26             j++;
27         }
28     }
29     else if(r>10)
30     {
31         j=0;
32         while(m!=0)
33         {
34             p=m%r;
35             m=m/r;
36             if(p<10) buff[j]=p+'0';
37             else buff[j]=p-10+'A';
38             j++;
39         }
40     }
41     for(i=0;i<j;i++)
42     {
43         buf[i]=buff[j-i-1];
44     }
45 }
46 
47 bool ispal(char buf[])
48 {
49     string str;    // 为了方便,我转换成string型的
50     str=buf;
51     int flag=true;
52     int i,j;
53     for(i=0, j=str.size()-1;i<=j;++i,--j)
54     {
55         if(str[i]!=str[j]) return false;
56     }
57     return true;
58 }
59 
60 int main()
61 {
62    freopen("palsquare.in","r",stdin);
63    freopen("palsquare.out","w",stdout);
64    cin>>n;
65    string real1,real2;
66    for(int i=1;i<=300;i++)
67    {
68        for(int j=0;j<100;j++) buf[j]='\0';
69        int flag=true;
70        change(i,n);
71        real1=buf;
72        change(i*i,n);
73        real2=buf;
74        if(!ispal(buf))
75        {
76            flag=false;
77            continue;
78        }
79        if(flag==true)  cout<<real1<<" "<<real2<<endl;
80    }
81    return 0;
82 }
posted on 2012-05-10 18:07  Zee、  阅读(391)  评论(0编辑  收藏  举报