USACO 1.2 Palindromic Squares

本文介绍了一个算法问题:在特定的数制下找出其平方数为回文数的所有整数。文章提供了完整的C++实现代码,并详细解释了如何将十进制数转换为指定进制数的过程以及判断该数是否为回文数的方法。
Palindromic Squares
Rob Kolstad

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.

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 first integer is the number whose square is palindromic; the second integer is the square itself.

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

这道题目还是用枚举做,要注意的是转化成n进制的时候  n>10 的情况
View Code
 1 /*
 2 ID: shuyang1
 3 PROG: palsquare
 4 LANG: C++
 5 */
 6 #include <iostream>
 7 #include <stdio.h>
 8 #include <string>
 9 using namespace std;
10 
11 int n;   //n表示进制数;
12 char buf[100];   //存放n进制数;
13 
14 void change(int m,int r)   //m为十进制数,r为进制数
15 {
16     char buff[100];
17     int p,q,i,j;
18     if(r<=10)
19     {
20         j=0;
21         while(m!=0)
22         {
23             p=m%r;
24             m=m/r;
25             buff[j]=p+'0';
26             j++;
27         }
28     }
29     else if(r>10)
30     {
31         j=0;
32         while(m!=0)
33         {
34             p=m%r;
35             m=m/r;
36             if(p<10) buff[j]=p+'0';
37             else buff[j]=p-10+'A';
38             j++;
39         }
40     }
41     for(i=0;i<j;i++)
42     {
43         buf[i]=buff[j-i-1];
44     }
45 }
46 
47 bool ispal(char buf[])
48 {
49     string str;    // 为了方便,我转换成string型的
50     str=buf;
51     int flag=true;
52     int i,j;
53     for(i=0, j=str.size()-1;i<=j;++i,--j)
54     {
55         if(str[i]!=str[j]) return false;
56     }
57     return true;
58 }
59 
60 int main()
61 {
62    freopen("palsquare.in","r",stdin);
63    freopen("palsquare.out","w",stdout);
64    cin>>n;
65    string real1,real2;
66    for(int i=1;i<=300;i++)
67    {
68        for(int j=0;j<100;j++) buf[j]='\0';
69        int flag=true;
70        change(i,n);
71        real1=buf;
72        change(i*i,n);
73        real2=buf;
74        if(!ispal(buf))
75        {
76            flag=false;
77            continue;
78        }
79        if(flag==true)  cout<<real1<<" "<<real2<<endl;
80    }
81    return 0;
82 }

转载于:https://www.cnblogs.com/shenshuyang/archive/2012/05/10/2494800.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值