USACO 1.2.4

来源:互联网 发布:淘宝店铺一键装修 编辑:程序博客网 时间:2024/04/26 23:29
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 12 43 911 12122 48426 676101 10201111 12321121 14641202 40804212 44944264 69696
这题本身并不难,我一开始看错题意了,还以为在十进制下输出结果呢!
进制转换要是注意细节。
/*ID: xinming2PROG: palsquareLANG: C++*/#include <cstdio>#include <cmath>#include <algorithm>#include <iostream>#include <cstring>#include <map>#include <string>#include <stack>using namespace std;char s[10];char a[10];bool is_pal(char *s){    int n = strlen(s);    for(int i = 0  ; i <= n / 2 ; i++)    {        if(s[i] != s[n - i - 1])return 0;    }    return 1;}void fun(int x , int k, char *s){    int a , b , c = 0 ;    b = x;    while(b >= k)    {        a = b % k;        b = b / k;        s[c++] = a + '0';    }    s[c] = b + '0';}int main(){    freopen("palsquare.in","r",stdin);    freopen("palsquare.out","w",stdout);    int k;    while(cin >> k)    {        memset(s , 0 , sizeof(s));        for(int i = 1 ; i <= 300 ; i++)        {            fun(i * i , k , s);            if(is_pal(s))            {                fun(i , k , a);                int n1 = strlen(s);                int n2 = strlen(a);                for(int i = n2 - 1 ;i >= 0 ; i--)                {                    if(a[i] > 9 + '0')printf("%c",a[i] + 'A' - '9' - 1);                    else printf("%c",a[i]);                }                printf(" ");                for(int i = n1 - 1;i>= 0 ; i--)                {                    if(s[i] > 9 + '0')printf("%c",s[i] + 'A' - '9' - 1);                    else printf("%c",s[i]);                }                printf("\n");            }        }    }    return 0;}/**/


原创粉丝点击