当前位置: 代码迷 >> 综合 >> USCAO Section 1.2 Palindromic Squares
  详细解决方案

USCAO Section 1.2 Palindromic Squares

热度:65   发布时间:2023-09-19 12:17:28.0

原题:
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.
题意:
输入一个进制n,求在十进制数1-300的平方数在n进制下为回文数的数并输出。
输出要求:原数字的n进制数和回文的n进制平方数。
题解:
水题,进制转换,要注意并没有要求原数字也在n进制下是回文数。

代码:

/* ID:newyear111 PROG: palsquare LANG: C++ */#include <iostream>
#include <fstream>
#include <string>
#include<algorithm>
using namespace std;
const int N=25;
ifstream fin("palsquare.in");
ofstream fout("palsquare.out");int n;
char base[N];
char s1[N*100],s2[N*100];
//生成用于进制转换的对应表 
void init(){for(int i=0;i<10;i++){base[i]=char(i+'0');}for(int i=10;i<=20;i++){base[i]=char('A'+i-10);}
// cout<<base<<endl;
}
//回文数判定函数 
bool isOK(char str[],int size){for(int i=0;i<size/2;i++){if(str[i]!=str[size-i-1])return false;}   return true;
}
//进制转换函数 
int change(char s[],int t){int r,num=0;while(t){r=t%n;t/=n;s[num++]=base[r];}   s[num]=0;return num; 
}void solve(int x){int xx=x*x;int sizeXX,sizeX;sizeX=change(s1,x);sizeXX=change(s2,xx);if(isOK(s2,sizeXX)){for(int i=sizeX-1;i>=0;i--)//进制转换后,s1要逆序输出,不然原数字是反过来的 fout<<s1[i];fout<<" "<<s2<<endl;}
}int main()
{   init();fin>>n;for(int i=1;i<=300;i++){solve(i);}   fin.close();fout.close();return 0;
}
  相关解决方案