USACO天梯--Palindromic Squares

本文介绍了一个简单的程序设计问题——寻找特定进制下其平方为回文数的整数。程序采用C++编写,通过转换整数到指定进制并检查回文特性来找出符合条件的数及其平方。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 theintegers N (1 <= N <= 300 base 10) such that the square of N ispalindromic when expressed in base B; also print the value of thatpalindromic square. Use the letters 'A', 'B', and so on to representthe 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. Thefirst integer is the number whose square is palindromic;the second integer is the square itself. NOTE WELL THATBOTH INTEGERS ARE IN BASE B!

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

回文串,简单题不多说什么。
以下是我的AC代码:
/*
ID:wang ming
PROG:palsquare
LANG:C++
*/
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
/*void strcpy(char b[],char *p)
{
    for(int i=0;*p=='\0';p++)
    {
        b[i++]=*p;
    }
}*/
int main()
{
	char a[100],b[100],c[100];
	freopen("palsquare.in","r",stdin);
	freopen("palsquare.out","w",stdout);
	int base;
	scanf("%d",&base);
	for(int i=1;i<=300;i++)
	{
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(c,0,sizeof(c));
		int temp1=i;
		int k=0;
		while(temp1!=0)
		{
			c[k++]=temp1%base+48;
			temp1/=base;
		 }
		 for(int j=0;j<=k-1;j++)
		if(c[j]>57)
		c[j]=c[j]-58+65;
		int temp=i*i;
		k=0;
		while(temp!=0)
		{
			a[k++]=temp%base+48;
			temp/=base;
		}
		for(int j=0;j<=k-1;j++)
		if(a[j]>57)
		a[j]=a[j]-58+65;
		//strcpy(b,a);
		k=0;
		for(int l=0;;l++)
		{
			if(a[l]=='\0')
			break;
			b[k++]=a[l];
		}
		//strrev(b);
		k=0;int len=strlen(a);
		while(k<(len/2))
		{
			char p=b[k];
			b[k]=b[len-1-k];
			b[len-1-k]=p;
			k++;
		}
		//strrev(c);
		k=0;len=strlen(c);
		while(k<(len/2))
		{
			char p=c[k];
			c[k]=c[len-1-k];
			c[len-1-k]=p;
			k++;
		}
		if(strcmp(b,a)==0)
		printf("%s %s\n",c,a);
	}
	return 0;
}


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值