您的位置:首页 > 其它

USACO section1.2 Palindromic Squares

2011-09-01 22:57 357 查看
PalindromicSquares
问题描述Question:

Palindromesare numbers that read the same forwards as backwards. The number12321 is a typical palindrome.
Givena number base B (2 <= B <= 20 base 10), print all the integersN (1 <= N <= 300 base 10) such that the square
of N ispalindromic when expressed in base B; also print the value of thatpalindromic square. Use the letters 'A', 'B', and so on to representthe digits 10, 11, and so on.
Printboth the number and its square in base B.

PROGRAMNAME: palsquare

INPUTFORMAT

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

SAMPLEINPUT (file palsquare.in)

10

OUTPUTFORMAT

Lineswith two integers represented in base B. The first integer is thenumber whose square is palindromic; the second
integer is the squareitself.

SAMPLEOUTPUT (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


问题翻译(来自sznoi):
回文平方数
回文数是指从左向右念和从右像做念都一样的数。如12321就是一个典型的回文数。
给定一个进制B(2<=B<=20十进制),输出所有的大于等于1小于等于300且它的平方用B进制表示时是回文数的数。用’A’,’B’……表示10,11等等。


PROGRAMNAME: palsquare


INPUTFORMAT

共一行,一个单独的整数B(B用十进制表示)。


SAMPLEINPUT (file palsquare.in)

10


OUTPUTFORMAT

每行两个数字,第二个数是第一个数的平方,且第二个数是回文数。(注意:这两个数都应该在B那个进制下)


SAMPLEOUTPUT (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


题解:
这道题是一道农夫山泉级别的题,难度不大但是在其中很有几个点卡人
这些我错过的点:
1.输出的两个数都是在B进制下的数
2.我在转换进制的时候没有把数翻转过来
这道题的数据范围只有1到300 平方也只有1到90000 不需要使用高精度

C代码:
#include <stdio.h>
#include <string.h>

char BASE[20] = {"0123456789ABCDEFGHIJ"};//进制字符
char num[20],square[20];
int scale;//保存B 表示几进制

void changebase(char *a, int n);//转换进制
int isPal();//是否是回文数

int main()
{
int i;
freopen("palsquare.in","r",stdin);
freopen("palsquare.out","w",stdout);

scanf("%d",&scale);
for(i=1;i<=300;i++) {
changebase(square, i*i);//把i的平方转化为B进制数
changebase(num, i);//把i转化为B进制数
if(isPal()) {//判断是否是回文数
printf("%s %s\n",b,a);
}
}
return 0;
}

void changebase(char *a, int n) {
int i = 0,len;
char t;

while(n>0) {
a[i] = BASE[n%scale];
n /= scale;
i++;
}
len = i;

//翻转数
for(i=0;i<len/2;i++) {
t=a[i];
a[i]=a[len-i-1];
a[len-i-1]=t;
}

a[len] = '\0';//一定要加上字符串的结束符
}

int isPal() {
int len,i;
len = strlen(square);

for(i=0;i<len;i++) {
if(square[i] != square[len-i-1]) {
return 0;//一旦有不相等的就返回0
}
}
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: