// David Poeschl // This solution was designed to be too slow. import java.util.*; public class RemovalTimeLimitExceededDavid { public static int bestAnswer; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int numValues = scan.nextInt(); while (numValues > 0) { bestAnswer = Integer.MAX_VALUE; List values = new ArrayList<>(); for (int i = 0; i < numValues; i++) values.add(scan.nextInt()); solve(values, 0); System.out.println(bestAnswer); numValues = scan.nextInt(); } scan.close(); } private static void solve(List values, int runningTotal) { if (values.size() == 2) { int total = runningTotal + gcd(values.get(0), values.get(1)); if (total < bestAnswer) bestAnswer = total; return; } for (int i = 0; i < values.size(); i++) { int leftVal = i != 0 ? values.get(i - 1) : values.get(values.size() - 1); int rightVal = i != values.size() - 1 ? values.get(i + 1) : values.get(0); List newValues = new ArrayList(values); newValues.remove(i); solve(newValues, runningTotal + gcd(leftVal, rightVal)); } } private static int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } }