CF BUDDY
← Problems·

1407B · Big Vova

1300 · brute force, greedy, math

Problem: Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.

You're given nn positive integers a1,a2,,ana_1, a_2, \dots, a_n. Using each of them exactly at once, you're to make such sequence b1,b2,,bnb_1, b_2, \dots, b_n that sequence c1,c2,,cnc_1, c_2, \dots, c_n is lexicographically maximal, where ci=GCD(b1,,bi)c_i=GCD(b_1,\dots,b_i) - the greatest common divisor of the first ii elements of bb.

Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.

A sequence aa is lexicographically smaller than a sequence bb if and only if one of the following holds:

  • aa is a prefix of bb, but aba \ne b;
  • in the first position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.

Input Format: Each test contains multiple test cases. The first line contains the number of test cases tt (1t1031 \le t \le 10^3). Description of the test cases follows.

The first line of each test case contains a single integer nn (1n1031 \le n \le 10^3)  — the length of the sequence aa.

The second line of each test case contains nn integers a1,,ana_1,\dots,a_n (1ai1031 \le a_i \le 10^3)  — the sequence aa.

It is guaranteed that the sum of nn over all test cases does not exceed 10310^3.

Output Format: For each test case output the answer in a single line  — the desired sequence bb. If there are multiple answers, print any.

Note: In the first test case of the example, there are only two possible permutations bb  — [2,5][2, 5] and [5,2][5, 2]: for the first one c=[2,1]c=[2, 1], for the second one c=[5,1]c=[5, 1].

In the third test case of the example, number 99 should be the first in bb, and GCD(9,3)=3GCD(9, 3)=3, GCD(9,8)=1GCD(9, 8)=1, so the second number of bb should be 33.

In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation bb.

Sample Cases

Case 1

Input

7
2
2 5
4
1 8 2 3
3
3 8 9
5
64 25 75 100 50
1
42
6
96 128 88 80 52 7
5
2 4 8 16 17

Output

5 2 
8 2 1 3 
9 3 8 
100 50 25 75 64 
42 
128 96 80 88 52 7 
17 2 4 8 16

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback