Algorithm, Data structure/Solved Algorithmic Problem

USACO 1.2 - Palindromic Squares

JaykayChoi 2016. 6. 8. 00:30

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. NOTE WELL THAT BOTH 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


출처: http://train.usaco.org/


Palindromes 은 앞으로 읽으나 뒤로 읽으나 똑같은 수입니다. 진수 B가 주어질 때 N의 제곱이 Palindromes 이라면 N 과 그 N의 제곱을 출력하는 문제입니다. 단, 10이상의 수는 대문자 알파벳을 A, B, C 순으로 사용하고 출력도 B진수로 출력해야됩니다. 


my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
 
 
string convertToBase(int number, int base)
{
    string ret;
    int temp = base;
 
    while (temp < number)
    {
        temp *= base;
    }
 
    while (true)
    {
        temp /= base;
 
        if (number / temp >= 10)
            ret += number / temp - 10 + 'A';
        else
            ret += number / temp + '0';
 
        number = number % temp;
 
        if (temp < 2)
            break;
    }
 
    return ret;
}
 
string reverseString(string str)
{
    string ret = "";
    for (int i = str.length() - 1; i >= 0; i--)
        ret += str[i];
    return ret;
}
 
bool isPalindromic(string str)
{
    return str == reverseString(str);
}
 
int main()
{
    ofstream fout("palsquare.out");
    ifstream fin("palsquare.in");
    int base;
    fin >> base;
 
    for (int i = 1; i <= 300++i)
    {
        string p = convertToBase(i * i, base);
        if (isPalindromic(p))
            fout << convertToBase(i, base) << " " << p << endl;
    }
 
    return 0;
}
 
cs


'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글

USACO 1.3 - Mixing Milk  (0) 2016.06.09
USACO 1.2 - Dual Palindromes  (0) 2016.06.08
USACO 1.2 - Name That Number  (1) 2016.06.06
USACO 1.2 - Transformations  (0) 2016.06.06
USACO 1.2 - Milking Cows  (0) 2016.06.05