Palindromic Squares
Rob Kolstad
Palindromes are numbers that read the same forwards as backwards. Thenumber 12321 is a typical palindrome.
Given a number base B (2 <= B <= 20 base 10), print all the integersN (1 <= N <= 300 base 10) such that the square of N is palindromic whenexpressed in base B; also print the value of that palindromic square. Use theletters '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 firstinteger is the number whose square is palindromic; the second integer is thesquare itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B!
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进制下为回文数,且为另一个数的平方,则称该数为B进制下的回文平方数。题目给出B(2≤B≤20),求出所有平方根不大于300的回文平方数,输出它们的平方根和它们。
这题就不用说了吧。。。从1到300枚举,将它们的平方转化为B进制,判断是否为回文数。若是,则输出。
代码附上:
/*
ID:su1q2d2
LANG:C++
TASK:palsquare
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#define maxnum 60
#define maxn 100
using namespace std;
char num[maxnum]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J'};
void cn(int n,int b,char ans[])
{
int i=0;
while(n>0){
ans[i]=num[n%b];
n/=b;
i++;
}
ans[i]='\0';
return ;
}
bool pal(char x[])
{
int i;
int n=strlen(x);
for(i=0;i<n;i++){
if(x[i]!=x[n-i-1]) return false;
}
return true;
}
char sqrr[maxn];
char base[maxn];
int main()
{
freopen("palsquare.in","r",stdin);
freopen("palsquare.out","w",stdout);
int B;
int n;
int i;
int j;
scanf("%d",&B);
for(i=1;i<=300;i++){
cn(i*i,B,sqrr);
if(pal(sqrr)){
cn(i,B,base);
n=strlen(base);
for(j=n-1;j>=0;j--) printf("%c",base[j]);
printf(" ");
n=strlen(sqrr);
for(j=0;j<n;j++) printf("%c",sqrr[j]);
printf("\n");
}
}
return 0;
}