2017-05-29
题目大意:
输入一个整数B(2<=B<=20 ),求所有的数N(1<=N<=300)使得N的平方在B进制下为回文数。输出时一行有两个数,N(也是B进制格式)和它在B进制下的平方表示。其中,10用’A’表示,11用’B’表示,以此类推。
回文数就是从左往右和从右往左一样的数,且最左和最右的数字不为0。
样例输入:
10
样例输出:
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和它的平方都要以B进制下的形式输出。因为求B进制数时是倒序的,所以输出N的B进制形式要倒着输出。至于它的平方则无所谓,因为本身就是回文数。
代码如下:
/*
ID: madara01
PROG: palsquare
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#define cin fin
#define cout fout
#define MAX 301
using namespace std;
char refers[21] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K'};
int base; //进制
string s; //base进制下平方的表示
string ori;//base进制下原数的表示
bool isPalindrome(string s) //判断s表示的数是否为回文数
{
int sl = s.length();
int l = sl/2 +1;
for(int i = 0; i<l; i++)
{
if(s[i] != s[sl-i-1]) return false;
}
return true;
}
bool result(int number) //判断number是否为符合题意的解
{
//末端为'0'不可能是回文数
if(number % base == 0) return false;
while(number)
{
s = s + refers[number%base];
number = number / base;
}
if(isPalindrome(s)) return true;
return false;
}
int main(int argc, char **argv)
{
ofstream fout ("palsquare.out");
ifstream fin ("palsquare.in");
int n,temp;
cin >> base;
for(n = 1; n < MAX; n++)
{
s = "";
ori = "";
temp = n;
if(result(n*n))
{
while(temp)
{
ori = ori + refers[temp%base];
temp = temp / base;
}
for(temp = ori.length() - 1; temp >= 0; temp --) cout << ori[temp];
cout << " " << s << endl;
}
}
return 0;
}