You are viewing a single comment's thread. Return to all comments →
WIsh I had known this. I did something like below which doesnt satisfy all cases :( #unneccessarilycomplicated
public static int generalizedGCD(int num, int[] arr) { // WRITE YOUR CODE HERE // check edge values for num if(num == 1) { return arr[0]; } // iterate over arr HashMap<Integer, Integer> divisors = new HashMap<Integer, Integer>(); for(int index = 0; index < num; index++) { int start = 2; while (start <= arr[index] / 2) { if (arr[index] % start == 0) { if (divisors.containsKey(start)) { int count = divisors.get(start); count++; divisors.put(start, count); } else divisors.put(start, 1); } start++; } } Iterator<Map.Entry<Integer,Integer>> itr = divisors.entrySet().iterator(); int maxCount = -1; int gcd = -1; while(itr.hasNext()) { Map.Entry<Integer, Integer> entry = itr.next(); if(maxCount < entry.getValue()) { maxCount = entry.getValue(); gcd = entry.getKey(); } } return maxCount==num-1 ? gcd : 1; // METHOD SIGNATURE ENDS }
Seems like cookies are disabled on this browser, please enable them to open this website
Computing the GCD
You are viewing a single comment's thread. Return to all comments →
WIsh I had known this. I did something like below which doesnt satisfy all cases :( #unneccessarilycomplicated