usaco1.2.4palsquare

题目:

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


题意蛮简单,就是输入一个数b ,输出 300以内的n 和 n的平方,要求n平方转换成b 进制后是回文数。直接枚举
错了一次,原因是输出 n 时没有把n转换成 b进制
代码:
/*
ID:614433244
PROG: palsquare
LANG: C++
*/
#include"iostream"
#include"cstdio"
int a[25];int bet;//存放转化为r进制后的数,300的平方90000约为2^20次方,25位足够
int num[301];
void change( int n,int m )//把n转换为m进制
{
    bet=1;
    while( n )
    {
        a[bet]=n%m;
        n=n/m;
        bet++;
    }
}
int bb[10];
int tt;
void cc( int n,int m )
{
    tt=1;
    while( n )
    {
        bb[tt]=n%m;
        n=n/m;
        tt++;
    }
}
bool isback()//判断数组a是否回文
{
    int l,r;
    for( l=1,r=bet-1;; )
    {
        if( l==r )
            return true;
        if( r-l==1&&a[r]==a[l] )
            return true;
        if( a[r]==a[l] )
        {
            l++;r--;
        }
        if( a[r]!=a[l] )
            return false;
    }
}

int main()
{
    freopen("palsquare.in","r",stdin);
    freopen("palsquare.out","w",stdout);
    int i,j;
    for( i=1;i<=300;i++ )
        num[i]=i*i;
    int b;
    scanf("%d",&b);
    for( i=1;i<=300;i++ )
    {
        change( num[i],b );
        if( isback() )
        {
//            printf("%d ",i);
            cc(i,b);
            for( j=tt-1;j>0;j-- )
            {
                if( bb[j]<10 )
                    printf("%d",bb[j]);
                else
                    printf("%c",'A'+(bb[j]-10));
            }
            printf(" ");
            for( j=1;j<bet;j++ )
            {
                if( a[j]<10 )
                    printf("%d",a[j]);
                else
                    printf("%c",'A'+(a[j]-10));
            }
            printf("\n");
        }
    }
    return 0;
}
posted @ 2012-06-02 15:44  萧若离  阅读(144)  评论(0)    收藏  举报