(SPOJ) Soma de Frações - Solution
Link to the problem: http://br.spoj.com/problems/SOMA13/
The solution below uses some Math concepts.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = br.readLine();
String[] s = line.split(" ");
int n1 = Integer.parseInt(s[0]);
int d1 = Integer.parseInt(s[1]);
int n2 = Integer.parseInt(s[2]);
int d2 = Integer.parseInt(s[3]);
int n = 0;
int d = 0;
if (d1 == d2) {
d = d1;
n = n1+n2;
}
else {
d = d1*d2;
n1 = d/d1*n1;
n2 = d/d2*n2;
n = n1+n2;
}
int min = Math.min(n, d);
for (int i = min; i >= 2; i--) {
if (n%i == 0 && d%i == 0) {
n /= i;
d /= i;
}
}
bw.write(n + " " + d + "\n");
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below uses some Math concepts.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = br.readLine();
String[] s = line.split(" ");
int n1 = Integer.parseInt(s[0]);
int d1 = Integer.parseInt(s[1]);
int n2 = Integer.parseInt(s[2]);
int d2 = Integer.parseInt(s[3]);
int n = 0;
int d = 0;
if (d1 == d2) {
d = d1;
n = n1+n2;
}
else {
d = d1*d2;
n1 = d/d1*n1;
n2 = d/d2*n2;
n = n1+n2;
}
int min = Math.min(n, d);
for (int i = min; i >= 2; i--) {
if (n%i == 0 && d%i == 0) {
n /= i;
d /= i;
}
}
bw.write(n + " " + d + "\n");
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment