Pages

Thursday, December 31, 2009

USACO: Palindromic Squares

/*
ID: wsoethe1
LANG: JAVA
TASK: palsquare
*/

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class palsquare {
public static void main(String[] args) {
try {
BufferedReader fileIn = new BufferedReader(new FileReader("palsquare.in"));
PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter("palsquare.out")));
try {
String line = "";
while ((line = fileIn.readLine()) != null) {
int base = new Integer(line).intValue();

// 1 to 300 in this base
for (int i = 1; i <= 300; i++) {
String iBase = getNumberByBase(i * i, base);

// palindromic squares
if (iBase.equals(stringReverse(iBase))) {
fileOut.write(getNumberByBase(i, base) + " " + iBase + "\n");
}
}
}
} finally {
fileIn.close();
fileOut.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
System.exit(0);
}

public static String stringReverse(String str) {
int len = str.length();
StringBuffer buffer = new StringBuffer(len);
for (int i = (len - 1); i >= 0; i--) {
buffer.append(str.charAt(i));
}
return buffer.toString();
}

private static String getNumberByBase(int n, int base) {
if (n == 0) {
return "0";
}

String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String s = "";
while (n > 0) {
int d = n % base;
s = digits.charAt(d) + s;
n = n / base;
}
return s;
}

}

No comments :