Obs: Resultado de uma prova de lógica que tive que fazer:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class mdc {
public static List<Integer> listPrimo = new ArrayList<Integer>();
private static int MAX_VALUE = 1000;
private static int MIN_VALUE = 1;
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
gerarPrimos(MAX_VALUE / 2 + 1);
String continua = "S";
while (continua.equalsIgnoreCase("s")) {
try {
int[] entrada = new int[3];
List<Integer>[] mmc = new ArrayList[3];
for (int i = 1; i <= 3; i++) {
String tmpInt = null;
while (tmpInt == null || !validaInt(tmpInt)) {
System.out.print("Entre com o " + i + "o valor: ");
tmpInt = in.readLine();
if (!validaInt(tmpInt)) {
System.out.println("valor errado!!!");
}
}
entrada[i - 1] = Integer.parseInt(tmpInt);
mmc[i - 1] = getMMC(entrada[i - 1]);
printMMC(mmc[i - 1]);
System.out.println();
}
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < mmc[0].size(); i++) {
if ((remove(mmc[0].get(i), mmc[1])) && (remove(mmc[0].get(i), mmc[2]))) {
result.add(mmc[0].get(i));
}
}
System.out.print("MDC: ");
String sep = "";
int multi = 1;
for (Integer i : result) {
System.out.print(sep + i.intValue());
sep = " * ";
multi *= i.intValue();
}
System.out.println(" = " + multi);
System.out.println();
System.out.print("Deseja continuar (s/n):");
continua = in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.print("fim.");
}
private static void printMMC(List l) {
System.out.print("MMC: ");
String sep = "";
for (Object i : l) {
int v = ((Integer) i).intValue();
System.out.print(sep + i);
sep = " + ";
}
System.out.println();
}
private static boolean remove(Integer v, List l) {
for (int i = 0; i < l.size(); i++) {
if (((Integer) l.get(i)).intValue() == v.intValue()) {
l.remove(i);
return true;
}
}
return false;
}
public static List<Integer> getMMC(int v) {
List<Integer> result = new ArrayList<Integer>();
int i = 0;
do {
if (v % listPrimo.get(i) == 0) {
v /= listPrimo.get(i);
result.add(listPrimo.get(i));
} else {
i++;
}
} while (v != 1);
return result;
}
private static boolean validaInt(String s) {
int v = -1;
try {
v = Integer.parseInt(s);
} catch (Exception e) {
return false;
}
if (v <= MAX_VALUE && v >= MIN_VALUE) {
return true;
}
return false;
}
public static void gerarPrimos(int ate) {
int count = 0;
System.out.println("gerando primos...");
for (int i = 2; i <= ate; i++) {
boolean ehPrimo = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
ehPrimo = false;
}
}
if (ehPrimo) {
listPrimo.add(i);
}
if (ate % 5 == 0) {
System.out.println(((count * 100) / ate) + "%");
}
count++;
}
System.out.println("primos OK...");
}
}
Nenhum comentário:
Postar um comentário