2015-12-25 4 views
0

Я пытался реализовать алгоритм Евклида в Java для 2-х номеров или more.The проблем с моим кодом, чтоОСУЩЕСТВЛЕНИЮ Евклида в Java

а) Он отлично работает на 2-х номера, но возвращает правильное значение несколько раз, когда вводится более двух чисел. Можем предположить, что это, вероятно, из-за операторов возврата в моем коде.

b) Я не совсем понимаю, как это работает. Хотя я сам его закодировал, я не совсем понимаю, как работают операторы return.

import java.util.*; 

public class GCDCalc { 

static int big, small, remainder, gcd; 

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    // Remove duplicates from the arraylist containing the user input. 

    ArrayList<Integer> listofnum = new ArrayList(); 
    System.out.println("GCD Calculator"); 
    System.out.println("Enter the number of values you want to calculate the GCD of: "); 
    int counter = sc.nextInt(); 

    for (int i = 0; i < counter; i++) { 
     System.out.println("Enter #" + (i + 1) + ": "); 
     int val = sc.nextInt(); 
     listofnum.add(val); 
    } 

    // Sorting algorithm. 
    // This removed the need of conditional statements(we don't have to 
    // check if the 1st number is greater than the 2nd element 
    // before applying Euclid's algorithm. 
    // The outer loop ensures that the maximum number of swaps are occurred. 
    // It ensures the implementation of the swapping process as many times 
    // as there are numbers in the array. 
    for (int i = 0; i < listofnum.size(); i++) { 
     // The inner loop performs the swapping. 
     for (int j = 1; j < listofnum.size(); j++) { 
      if (listofnum.get(j - 1) > listofnum.get(j)) { 
       int dummyvar = listofnum.get(j); 
       int dummyvar2 = listofnum.get(j - 1); 
       listofnum.set(j - 1, dummyvar); 
       listofnum.set(j, dummyvar2); 

      } 
     } 
    } 

    // nodup contains the array containing the userinput,without any 
    // duplicates. 
    ArrayList<Integer> nodup = new ArrayList(); 
    // Remove duplicates. 
    for (int i = 0; i < listofnum.size(); i++) { 
     if (!nodup.contains(listofnum.get(i))) { 
      nodup.add(listofnum.get(i)); 
     } 
    } 

    // Since the array is sorted in ascending order,we can easily determine 
    // which of the indexes has the bigger and smaller values. 
    small = nodup.get(0); 
    big = nodup.get(1); 
    remainder = big % small; 

    if (nodup.size() == 2) { 
     recursion(big, small, remainder); 
    } else if (nodup.size() > 2) { 
     largerlist(nodup, big, small, 2); 
    } else // In the case,the array only consists of one value. 
    { 
     System.out.println("GCD: " + nodup.get(0)); 
    } 
} 

// recursive method. 
public static int recursion(int big, int small, int remainder) { 
    remainder = big % small; 
    if (remainder == 0) { 
     System.out.println(small); 
    } else { 
     int dummyvar = remainder; 
     big = small; 
     small = dummyvar; 
     recursion(big, small, remainder); 
    } 
    return small; 
} 

// Method to deal with more than 2 numbers. 
public static void largerlist(ArrayList<Integer> list, int big, int small, int counter) { 
    remainder = big % small; 
    gcd = recursion(big, small, remainder); 

    if (counter == list.size()) { 

    } else if (counter != list.size()) { 
     big = gcd; 
     small = list.get(counter); 
     counter++; 
     largerlist(list, gcd, small, counter); 
    } 

    } 
} 

Я заранее извиняюсь за ошибки форматирования и т.д. Любые предложения были бы было оценено!

+0

См. Этот ответ [здесь:] (http://stackoverflow.com/questions/27004830/how-to-write-extended-euclidean-algorithm-code-wise-in-java) – Perdomoff

+0

Не уверен, что остальная часть Это. Но если вы хотите сортировать и удалять дубликаты, я просто бросаю числа в TreeSet. Устраните это, по крайней мере, рывок. – yngwietiger

+0

FYI, здесь [1-строчная реализация Java, если алгоритм Евклида] (http://stackoverflow.com/a/6619618/256196) – Bohemian

ответ

0

Я думаю, что эти два задания являются неправильный путь вокруг

big = gcd; 
    small = list.get(counter); 

, а затем big не используется

largerlist(list, gcd, small, counter); 

Также вы использовали статические переменные, которые, как правило, является проблемой.

Предлагаю удалить статические/глобальные переменные и, как правило, не использовать повторно используемые переменные.

Редактировать: О да, return. Вы проигнорировали возвращаемое значение метода recursion при вызове метода recursion. Это не имеет значения, поскольку вы печатаете вместо того, чтобы возвращать значение, но такие решения ломаются, когда, скажем, вы хотите использовать эту функцию более одного раза.