Thursday, January 13, 2011

Facebook Hacker Cup - Double Squares Solution

Here's my java solution for the Double Squares problem in the Facebook Hacker Cup

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Date;

public class Squares {

public Squares(int square) {

double squareRoot = Math.sqrt(square);
int squareCount = 0;
for (int counter1 = 0; counter1 <= squareRoot; counter1++) {

for (int counter2 = counter1; counter2 <= squareRoot; counter2++) {

if((counter1 * counter1) + (counter2 * counter2) == square)
squareCount++;

}

}
System.out.println(squareCount);
}

public static void main(String[] args) {

BufferedReader input = null;
try {

input = new BufferedReader(new FileReader("squares.txt"));
String inputLine = input.readLine();
Integer squares = Integer.parseInt(inputLine);
for(int counter = 0; counter < squares; counter++) {

new Squares(Integer.parseInt(input.readLine()));

}
input.close();

}
catch(Exception e) {

System.out.println("e.getMessage():" + e.getMessage());
e.printStackTrace();

}

}
}

Results in less than a minute

No comments: