Нахождение наибольшего общего делителя JAVA (javarush)
Не понимаю, что может быть не так?
Наибольший общий делитель (НОД). Ввести с клавиатуры 2 целых положительных числа. Вывести в консоль наибольший общий делитель.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class NOD {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String X = reader.readLine();
String Y = reader.readLine();
reader.close();
if (X.indexOf("-",0) == -1 || Y.indexOf("-",0) == -1) {
try {
int x = Integer.parseInt(X);
int y = Integer.parseInt(Y);
System.out.println(MostCommonЬultiple(x, y));
} catch (Exception e) {}
} else {}
}
public static int MostCommonЬultiple(int x, int y){
List<Integer> arrayX = del(x);
List<Integer> arrayY = del(y);
List<Integer> XandY = CompareArray(arrayX,arrayY);
return MaxOfCom(XandY);
}
public static List<Integer> del(int a){
List<Integer> divider = new ArrayList<>();
for (int i = 1; i <= a; i++) {
if (a % i == 0) {
divider.add(i);
}
}
return divider;
}
public static List<Integer> CompareArray(List<Integer> a, List<Integer> b){
List<Integer> compare = new ArrayList<>();
for (int i = 0; i < a.size(); i++){
for (int j = 0; j < b.size(); j++){
if (a.get(i).equals(b.get(j))) compare.add(a.get(i));
}
}
return compare;
}
public static int MaxOfCom(List<Integer> a){
int max = a.get(0);
for (int i = 0; i<a.size();i++){
if(max<a.get(i)) max = a.get(i);
}
return max;
}
}
Ответы (2 шт):
Автор решения: Дмитрий
→ Ссылка
Для такой простой задачи это слишком сложный код. Всегда помните про KISS.
import java.util.Scanner;
public class NOD {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
int nod = mostCommonMultiple(Integer.valueOf(sc.nextLine()),Integer.valueOf(sc.nextLine()));
System.out.println("NOD: " + nod);
} catch (NumberFormatException | UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
}
private static int mostCommonMultiple(int x, int y) {
if (x<=0 || y<=0) throw new UnsupportedOperationException("Incorrect input");
while(x!=0 && y!=0){
if (x>y) x=x%y;
else y=y%x;
}
return x+y;
}
}
Автор решения: Viktor Tsiabus
→ Ссылка
Tак проще:
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int count;
int x = 0;
int y = 0;
try {
x = Integer.parseInt(reader.readLine());
y = Integer.parseInt(reader.readLine());
} catch (Exception e){
System.out.println("Введи с клавиатуры 2 целых положительных числа.");
} finally {
reader.close();
}
count = Math.min(x, y);
for (int n = count; n >= 1; n--){
if (x % n == 0 && y % n == 0){
count = n;
break;
}
}
System.out.println(count);
}