(UVA) Fractions Again?! - Solution

I used Brute Force to solve this problem.
 

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 number = Integer.parseInt(line);
           
            int count = 0;
            ArrayList<Pair> pairs = new ArrayList<Pair>();
            for (int i = number+1; i <= (number+1)*(number+1); i++) {
                if (((i*number)%(i-number)) == 0) {
                    pairs.add(new Pair((i*number)/(i-number), i));
                    count++;
                }
                if ((i*number)/(i-number) < i) {
                    break;
                }
            }         
           
            Collections.sort(pairs);
           
            System.out.println(count);
            for (int i = 0; i < pairs.size(); i++) {
                System.out.println("1/" + number + " = 1/" + pairs.get(i).num1 + " + 1/" + pairs.get(i).num2);
            }
                      
            line = br.readLine();
        }
                   
        return;
    }
  
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();

        System.exit(0);
    }
}

class Pair implements Comparable<Pair> {
    int num1;
    int num2;
   
    public Pair(int n1, int n2) {
        num1 = n1;
        num2 = n2;
    }
   
    public int compareTo(Pair p) {
        return this.num2-p.num2;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução