1. 程式人生 > >#161-[進位制轉換]迴文平方數

#161-[進位制轉換]迴文平方數

Description

迴文數是指從左向右念和從右向左念都一樣的數。如12321就是一個典型的迴文數。

給定一個進位制B(2<=B<=20,由十進位制表示),輸出所有的大於等於1小於等於300(十進位制下)且它的平方用B進製表示時是迴文數的數。用’A’,’B’……表示10,11等等

Input

共一行,一個單獨的整數B(B用十進位制表示)。

Output

每行兩個B進位制的符合要求的數字,第二個數是第一個數的平方,且第二個數是迴文數。

Sample Input

10

Sample Output

1 1
2 4
3 9
11 121
22 484
26 676
101 10201
111 12321
121 14641
202 40804
212 44944
264 69696

直接進位制轉換然後判斷

#include <iostream>
#include <cstdio>
#include <cstring>

#define SIZE 210

using namespace std;

int a[SIZE], temp[SIZE], n, len, len2;

bool check(void) // 判斷迴文
{
	int i;
	
	for (i = 1; i <= len2; ++i)
	{
		if (temp[i] != temp[len2-i+1])
		{
			return false;
		}
	}
	
	return true;
}

void mul(void) // 高精度乘
{
	int i, j;
	
	len2 = len << 1;
	memset(temp, 0, sizeof (temp));
	for (i = 1; i <= len; ++i)
	{
		for (j = 1; j <= len; ++j)
		{
			temp[i+j-1] += a[i] * a[j];
		}
	}
	for (i = 1; i <= len2; ++i)
	{
		if (temp[i] >= n)
		{
			temp[i+1] += temp[i] / n;
			temp[i] %= n;
		}
	}
	while (!temp[len2])
	{
		--len2;
	}
	
	return;
}

int main(void)
{
	int i, j, temp;
	
	scanf("%d", &n);
	
	for (i = 1; i <= 300; ++i)
	{
		memset(a, 0, sizeof (a));
		temp = i;
		len = 0;
		while (temp) // 進位制轉換
		{
			a[++len] = temp % n;
			temp /= n;
		}
		mul();
		if (check())
		{
			for (j = len; j; --j)
			{
				if (a[j] > 9)
				{
					printf("%c", 'A' + a[j] - 10);
				}
				else
				{
					printf("%d", a[j]);
				}
			}
			printf(" ");
			for (j = len2; j; --j)
			{
				if (::temp[j] > 9)
				{
					printf("%c", 'A' + ::temp[j] - 10);
				}
				else
				{
					printf("%d", ::temp[j]);
				}
			}
			printf("\n");
		}
	}
	
	return 0;
}