回文数是指从左向右念和从右像做念都一样的数。如12321就是一个典型的回文数。 给定一个进制B(2<=B<=20十进制),输出所有的大于等于1小于等于300且它的平方用B进制表示时是回文数的数。用’A’,’B’……表示10,11等等。
输入描述:
共一行,一个单独的整数B(B用十进制表示)。
输出描述:
每行两个数字,第二个数是第一个数的平方,且第二个数是回文数。(注意:这两个数都应该在B那个进制下)
输入样例:
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鉴于网上用c++写此题的代码较少,遂发表此代码
#include <iostream> #include <cmath> using namespace std; void B10(int b, int i, int t) { int a[10000]; int c[10000]; int top=-1; int top1=-1; int flag=1; int j; while (i%b != i) { a[++top]=i%b; i = floor(i/b); } a[++top]=i%b; while (t%b != t) { c[++top1]=t%b; t = floor(t/b); } c[++top1]=t%b; for (j=0; j <= floor(top/2); j++) if (a[j] != a[top-j]) { flag=0; break; } if (flag == 1) { for (j=top1; j >= 0; j--) cout<<c[j]; cout<<" "; for (j=top; j >= 0; j--) cout<<a[j]; cout<<endl; } } void B20(int b, int i, int t) { char s[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','H','I','J','K'}; char a[10000]; char c[10000]; int top=-1; int top1=-1; int flag=1; int j; while (i%b != i) { a[++top]=s[i%b]; i = floor(i/b); } a[++top]=s[i%b]; while (t%b != t) { c[++top1]=s[t%b]; t = floor(t/b); } c[++top1]=s[t%b]; for (j=0; j <= floor(top/2); j++) if (a[j] != a[top-j]) { flag=0; break; } if (flag == 1) { for (j=top1; j >= 0; j--) cout<<c[j]; cout<<" "; for (j=top; j >= 0; j--) cout<<a[j]; cout<<endl; } } int main() { int i; int b; cin>>b; if (b <= 10) { for (i=1; i <= 300; i++) B10(b, i*i, i); } else { for (i=1; i <= 300; i++) B20(b, i*i, i); } return 0; }
此代码较好理解,分10进制以下及11到20进制的情况(因能力有限,实在不好整合,造成代码过于臃肿)
10进制以下好说,用求k取余法,重点看循环条件
11到20的话差不多,需要注意的是将大于10的数用相应的字母替代,为了方便,可将所有可能放在字符数组中
个人新博客地址:www.zsfblues.com