(UVA) Quirksome Squares - Solution 1

I used Brute Force to solve this problem.

I considered only the numbers that have an exact square. Once a Quirksome Square is a number 'xyzw' where (xy+zw)^2 = xyzw, these numbers are the only possible answers.
 

import java.io.*;
import java.util.*;

class Main  {
    public static void process() throws NumberFormatException, IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      
        String line = br.readLine();
        while (line != null) {
            int numDigits = Integer.parseInt(line);
          
            int div = 1;
            for (int i = 0; i < numDigits; i+=2) {
                div *= 10;
            }
          
            StringBuilder end = new StringBuilder();
            for (int i = 0; i < numDigits; i++) {
                end.append(9);
            }
            int size = Integer.parseInt(end.toString());

            ArrayList<Integer> quirksomeSquares = new ArrayList<Integer>();
            for (int i = 0; i*i <= size; i++) {
                int firstHalf = (i*i)/div;
                int secondHalf = (i*i)%div;
                if ((firstHalf+secondHalf)*(firstHalf+secondHalf) == (i*i)) {
                    quirksomeSquares.add((i*i));
                }
            }
          
            for (int i = 0; i < quirksomeSquares.size(); i++) {
                int iLenght = Integer.toString(quirksomeSquares.get(i)).length();
                for (int j = 0; j < (numDigits-iLenght); j++) {
                    System.out.print("0");
                }
                System.out.println(quirksomeSquares.get(i));
            }
          
            line = br.readLine();
        }
                      
        return;
    }
 
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();

        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução