I'm trying to create an algorithm to find the GCD. I know that there is a better way to resolve it, but I'm stuck in this problem: I'm using a map with Key = Divisor and Value = ArrayList of the numbers to divide.
I'd like to create a new ArrayList for each key, but I'm continuing to populate the same ArrayList.
Map<Integer,ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>();
int[] arr = {9,27,63}; //input
ArrayList <Integer> v= new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
for (int div = 1 ; div < arr[i]; div++) {
map.put(div, v);
if ((arr[i] % div) == 0) {
v.add(arr[i]);
}
}
}
int result;
//print
for (Map.Entry<Integer,ArrayList<Integer>> entry:map.entrySet()) {
System.out.print("Key: "+(int)entry.getKey());
System.out.print("");
for(Integer in: entry.getValue()){
System.out.print("-> "+in + " ");
}
System.out.println();
//if size of ArrayList == arr input -> is a common divisor. The Greatest is the MCD
if (entry.getValue().size() == arr.length){
max = (int)entry.getKey();
}
}
System.out.println("Result: "+ result); //ERROR
}
Output Example:
Key: 57-> 9 -> 9 -> 27 -> 27 -> 27 -> 63 -> 63 -> 63 -> 63 -> 63
Key: 58-> 9 -> 9 -> 27 -> 27 -> 27 -> 63 -> 63 -> 63 -> 63 -> 63
Key: 59-> 9 -> 9 -> 27 -> 27 -> 27 -> 63 -> 63 -> 63 -> 63 -> 63
It's obvious that 57 can't divide 9, so this List should be clear. So, every time I find a divisor, I put it in the same list. Can someone help me?