import java.util.*;
public class Main {
public static void main(String[] args) {
int[] A = {2, 1, 4, 8, 16, 32, 5};
int[][] result = findPermutation(A);
System.out.print("A = ");
for (int i = 0; i < result[1].length; i++) {
System.out.print(result[1][i] + " ");
}
System.out.println();
System.out.print("B = ");
for (int i = 0; i < result[0].length; i++) {
System.out.print(result[0][i] + " ");
}
}
public static int[][] findPermutation(int[] A) {
List<int[][]> sv = new ArrayList<>();
Arrays.sort(A);
List<int[]> permArr = permute(A);
for (int i = 0; i < permArr.size(); i++) {
int[] permutation = permArr.get(i);
int x = 0;
int[] B = new int[A.length];
for (int j = 0; j < permutation.length; j++) {
x = gcd(x, permutation[j]);
B[j] = x;
}
sv.add(new int[][]{B, permutation});
}
Collections.sort(sv, (a, b) -> {
int aSum = 0;
int bSum = 0;
for (int i = 0; i < a[0].length; i++) {
aSum += a[0][i];
bSum += b[0][i];
}
return Integer.compare(bSum, aSum);
});
return sv.get(0);
}
public static List<int[]> permute(int[] perms) {
List<int[]> results = new ArrayList<>();
if (perms.length <= 1) {
results.add(perms);
return results;
}
for (int i = 0; i < perms.length; i++) {
int current = perms[i];
int[] remaining = new int[perms.length - 1];
System.arraycopy(perms, 0, remaining, 0, i);
System.arraycopy(perms, i + 1, remaining, i, perms.length - i - 1);
List<int[]> innerPermutations = permute(remaining);
for (int j = 0; j < innerPermutations.size(); j++) {
int[] innerPermutation = innerPermutations.get(j);
int[] res = new int[perms.length];
res[0] = current;
System.arraycopy(innerPermutation, 0, res, 1, innerPermutation.length);
results.add(res);
}
}
return results;
}
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}