如何使此程序适用于USACO Training Pages Square Palindromes的输入> 10?

时间:2016-07-13 06:17:25

标签: algorithm search adhoc

问题陈述 -

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.

输入格式

带有B的单行,基数(在基数10中指定)。

示例输入

10

输出格式

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. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B!

示例输出

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

我的代码适用于所有输入&lt; = 10,但是,为输入&gt; 10提供了一些奇怪的输出。

我的代码 -

#include<iostream>
#include<cstdio>
#include<cmath>

using namespace std;

int baseToBase(int num, int base)  //accepts a number in base 10 and the base to be converted into as arguments
{                                  
    int result=0, temp=0, i=1;

    while(num>0)
    {
        result = result + (num%base)*pow(10, i);
        i++;
        num = num/base;
    }

    result/=10;
    return result;  
}

long long int isPalin(int n, int base) //checks the palindrome
{   
    long long int result=0, temp, num=n*n, x=n*n;

    num = baseToBase(num, base);
    x = baseToBase(x, base);

    while(num)
    {
        temp=num%10;
        result = result*10 + temp;
        num/=10;    
    }   

    if(x==result) 
        return x;
    else
        return 0;
}

int main()
{       
    int base, i, temp;
    long long int sq;
    cin >> base;

    for(i=1; i<=300; i++)
    {
        temp=baseToBase(i, base);
        sq=isPalin(i, base);

        if(sq!=0)
            cout << temp << " " << sq << endl;
    }

    return 0;
}

对于输入= 11,答案应为

1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
101 10201
111 12321
121 14641
202 40804
212 44944
234 53535

虽然我的回答是

1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
110 10901
101 10201
111 12321
121 14641
209 40304
202 40804
212 44944
227 50205
234 53535

我的输出和所需输出有所不同,因为202显示在209以下,110显示在101之前。

帮助表示感谢,谢谢!

1 个答案:

答案 0 :(得分:0)

B = 11显示基本转换错误的一个简单示例i = 10 temp应为A,但您的代码会计算temp = 10。因为我们只有10个符号0-9来完美地显示基数10或更低的每个数字,但是对于大于此的基数,你必须使用其他符号来表示不同的数字,如'A', 'B' and so on。问题描述明确指出。希望您现在可以通过修改int baseToBase(int num, int base)功能来修复代码。