Palindromic Squares


/*
ID: tausiq11
PROG: palsquare
LANG: C++
*/

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

char a [100];

bool is_palin (char x [])
{
    int length = strlen (x);

    for ( int i = 0; i < length / 2; i++ ) {
        if ( x [i] != x [length - 1 - i] )
            return false;
    }

    return true;
}

void base_conversion (int number, int base)
{
    int index = 0;

    while ( number ) {
        int mod = number % base;
        if ( mod > 9 ) {
            switch (mod) {
                case 10 :
                a [index++] = 'A';
                break;

                case 11 :
                a [index++] = 'B';
                break;

                case 12 :
                a [index++] = 'C';
                break;

                case 13 :
                a [index++] = 'D';
                break;

                case 14 :
                a [index++] = 'E';
                break;

                case 15 :
                a [index++] = 'F';
                break;

                case 16 :
                a [index++] = 'G';
                break;

                case 17 :
                a [index++] = 'H';
                break;

                case 18 :
                a [index++] = 'I';
                break;

                case 19 :
                a [index++] = 'J';
                break;
            }
        }

        else
            a [index++] = mod + '0';

        number /= base;
    }

    a [index++] = 0;
}

void reverse ()
{
    int length = strlen (a);

    for ( int i = 0; i < length / 2; i++ )
        swap (a [i], a [length - 1 - i] );
}

int main ()
{
    freopen ("palsquare.in", "r", stdin);
	freopen ("palsquare.out", "w", stdout);

    int base;
    scanf ("%d", &base);

    for ( int i = 1; i <= 300; i++ ) {

        base_conversion (i * i, base);

        if ( is_palin (a) ) {
            char temp [100];
            strcpy (temp, a);
            base_conversion (i, base);
            reverse ();
            printf ("%s %s\n", a, temp);
        }
    }

    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s