2015-12-25 3 views
0

J'ai essayé de mettre en œuvre l'algorithme d'Euclide en Java pour le problème 2 chiffres ou plus.Le avec mon code est queImplémentation algorithme d'Euclide en Java

a) Il fonctionne très bien pour les 2 chiffres, mais renvoie la valeur correcte plusieurs fois quand plus de 2 nombres sont entrés. Ma conjecture est que c'est probablement à cause des déclarations de retour dans mon code. B) Je ne comprends pas très bien comment cela fonctionne. Bien que je l'ai codé moi-même, je ne comprends pas très bien comment fonctionnent les instructions de retour.

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); 
    } 

    } 
} 

J'excuse à l'avance pour toutes les erreurs de formatage etc. Toutes les suggestions seraient appreciated.Thanks!

+0

Voir cette réponse [ici:] (http://stackoverflow.com/questions/27004830/how-to-wext-extended-euclidean-algorithm-code-wise-in-java) – Perdomoff

+0

Je ne sais pas pour le reste de il. Mais si vous voulez trier et supprimer des dups, je voudrais juste jeter les nombres dans un TreeSet. Éliminer ce croupion, au moins. – yngwietiger

+0

FYI, voici une [implémentation Java en 1 ligne si l'algorithme d'euclid] (http://stackoverflow.com/a/6619618/256196) – Bohemian

Répondre

0

Je pense que ces deux missions sont dans le mauvais sens

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

puis big non utilisé

largerlist(list, gcd, small, counter); 

Aussi, vous avez utilisé des variables statiques, ce qui est généralement un problème.

Je suggère de supprimer les variables statiques/globales et ne réutilise généralement pas les variables.

Édition: Oh oui, return. Vous avez ignoré la valeur de retour de la méthode recursion lorsqu'elle a été appelée à partir de la méthode recursion. Cela ne devrait pas avoir d'importance car vous imprimez au lieu de renvoyer la valeur, mais de telles solutions se rompent lorsque, disons, vous souhaitez utiliser la fonction plus d'une fois.