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 $n$ positive integers $a_1, a_2, \dots, a_n$. Using each of them exactly at once, you're to make such sequence $b_1, b_2, \dots, b_n$ that sequence $c_1, c_2, \dots, c_n$ is lexicographically maximal, where $c_i=GCD(b_1,\dots,b_i)$ - the greatest common divisor of the first $i$ elements of $b$. 

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

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



 $a$ is a prefix of $b$, but $a \ne b$;

 in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.


-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). Description of the test cases follows.

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

The second line of each test case contains $n$ integers $a_1,\dots,a_n$ ($1 \le a_i \le 10^3$)  — the sequence $a$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^3$.


-----Output-----

For each test case output the answer in a single line  — the desired sequence $b$. If there are multiple answers, print any.


-----Example-----
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 



-----Note-----

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

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

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 $b$.

Source: codeforces | Difficulty: EASY
Tags: Number theory

Complete search

Mathematics

Greedy algorithms


Solutions:
import os
import sys
from math import *
from collections import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 998244353
EPS = 1e-06

def Gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	a = array()
	a.sort(reverse=True)
	gc = a[0]
	ans = []
	vis = defaultdict(int)
	for i in range(n):
		here = 0
		hec = 0
		for j in range(n):
			if not vis[j]:
				temp = gcd(gc, a[j])
				if temp > hec:
					hec = temp
					here = j
		gc = hec
		vis[here] = True
		ans.append(a[here])
	print(*ans)


from math import gcd
T = int(input())
for t in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	maxx = max(A)
	curr_gcd = maxx
	res = [maxx]
	A.remove(maxx)
	for j in range(n - 1):
		temp = 1
		elem = 0
		for i in range(len(A)):
			temp2 = gcd(curr_gcd, A[i])
			if temp2 > temp:
				temp = temp2
				elem = i
		res.append(A[elem])
		curr_gcd = temp
		A = A[:elem] + A[elem + 1:]
	for x in res:
		print(x, end=' ')
	print()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ci = max(a)
	fin = []
	while a:
		curr = max(((gcd(ci, val), val) for val in a))
		a.remove(curr[1])
		fin.append(curr[1])
		ci = curr[0]
	print(*fin)


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = list()
	b = [0] * n
	mm = max(a)
	ans.append(mm)
	maxi = -math.inf
	for k in range(n):
		if a[k] == mm:
			b[k] = 1
			break
	GG = mm
	cc = -1
	for i in range(n - 1):
		maxi = -math.inf
		for j in range(n):
			if b[j] != 1:
				temp = math.gcd(GG, a[j])
				if temp > maxi:
					maxi = temp
					bb = a[j]
					cc = j
			if j == n - 1:
				GG = maxi
				ans.append(bb)
				if cc != -1:
					b[cc] = 1
	for i in range(len(ans)):
		print(ans[i], end=' ')
	print()


from math import gcd
t = int(input())
while t != 0:
	n = int(input())
	a = list(map(int, input().split()))[:n]
	ans = [max(a)]
	g = [max(a)]
	a.remove(max(a))
	for i in range(n - 1):
		high = 0
		maxi = 0
		for j in a:
			high = gcd(g[-1], j)
			if high > maxi:
				maxi = high
				k = j
		ans.append(k)
		g.append(maxi)
		a.remove(k)
	print(*ans)
	t -= 1


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	vis = [0] * n
	last = 0
	for i in range(n):
		last = max(last, a[i])
	for i in range(n):
		if a[i] == last:
			vis[i] = 1
			break
	print(last, end=' ')
	p = last
	for j in range(1, n):
		(maxi, pos) = (0, 0)
		for i in range(n):
			if vis[i]:
				continue
			if gcd(p, a[i]) > maxi:
				maxi = gcd(p, a[i])
				pos = i
		vis[pos] = 1
		print(a[pos], end=' ')
		p = maxi
	print()


from math import gcd as GCD
t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	checked = [False] * n
	(rem, mx) = (-1, 0)
	for (idx, num) in enumerate(ar):
		if num > mx:
			mx = num
			rem = idx
	checked[rem] = True
	gcd = mx
	print(mx, end=' ')
	for i in range(n - 1):
		(rem, var) = (-1, 0)
		for (idx, num) in enumerate(ar):
			if not checked[idx] and GCD(gcd, num) > var:
				var = GCD(gcd, num)
				rem = idx
		checked[rem] = True
		gcd = var
		print(ar[rem], end=' ')
	print()


import math

def main():
	n = int(input())
	lst = list(map(int, input().split()))
	cur = max(lst)
	res = [lst.index(cur)]
	st = set()
	st.add(lst.index(cur))
	for i in range(n - 1):
		el = -1
		mx = 0
		for k in range(n):
			if k in st:
				pass
			elif math.gcd(cur, lst[k]) > mx:
				mx = math.gcd(cur, lst[k])
				el = k
		st.add(el)
		res.append(el)
		cur = mx
	for i in res:
		print(lst[i], end=' ')
	print()
t = int(input())
for i in range(t):
	main()


import heapq
from collections import *
import math

def solve():
	n = int(input())
	a = [int(i) for i in input().split()]
	d = max(a)
	l = defaultdict(int)
	for i in a:
		l[i] += 1
	l[d] -= 1
	ans = [d]
	for i in range(n):
		maxi = 0
		t = 0
		for i in range(n):
			if math.gcd(d, a[i]) > maxi and l[a[i]] != 0:
				maxi = math.gcd(d, a[i])
				t = a[i]
		ans.append(t)
		d = math.gcd(d, t)
		l[t] -= 1
	print(*ans[:-1])
t = int(input())
for _ in range(t):
	solve()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	xo = 0
	ans = []
	while l:
		t = max(l, key=lambda x: gcd(x, xo))
		xo = gcd(t, xo)
		ans.append(t)
		l.remove(t)
	print(*ans)


import math
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	idx = 0
	maxi = 0
	for i in range(n):
		if a[i] > maxi:
			maxi = a[i]
			idx = i
	a.pop(idx)
	b = [maxi]
	n -= 1
	prev_gcd = maxi
	while n != 0:
		nex = 0
		maxi = 0
		idx = 0
		for i in range(n):
			temp = math.gcd(prev_gcd, a[i])
			if temp > maxi:
				maxi = temp
				nex = a[i]
				idx = i
		prev_gcd = maxi
		b.append(nex)
		a.pop(idx)
		n -= 1
	print(*b)


def computeGCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lexo(alist):
	gcd = max(alist)
	flist = []
	flist.append(gcd)
	alist.remove(gcd)
	while len(alist):
		oval = 0
		val = 0
		for a in alist:
			g = computeGCD(a, gcd)
			if g > val:
				val = g
				oval = a
		gcd = val
		flist.append(oval)
		alist.remove(oval)
	print(*flist)
t = int(input())
for it in range(t):
	n = int(input())
	x = input()
	alist = [int(i) for i in x.split()]
	lexo(alist)


from sys import stdin, stdout
from math import gcd
test = int(stdin.readline())
for _ in range(test):
	n = int(stdin.readline())
	a = [int(x) for x in stdin.readline().split()]
	a.sort(reverse=True)
	b = [max(a)]
	gg = [max(a)]
	(ma, mi) = (0, 0)
	cnt = 1
	s = [False for i in range(n)]
	s[0] = True
	while cnt < n:
		(ma, mi) = (0, 0)
		for i in range(n - 1, -1, -1):
			if not s[i]:
				g = gcd(gg[-1], a[i])
				if g > ma:
					ma = g
					mi = i
		gg.append(ma)
		b.append(a[mi])
		cnt += 1
		s[mi] = True
	print(*b)


def gcd(a, b):
	(a, b) = (max(a, b), min(a, b))
	while b > 0:
		(a, b) = (b, a % b)
	return a

def calc(a):
	a.sort()
	max_val = a[-1]
	del a[-1]
	res = [max_val]
	res_gcd = max_val
	while a:
		(val, pos) = (0, 0)
		for (i, item) in enumerate(a):
			v = gcd(res_gcd, item)
			if v > val:
				val = v
				pos = i
		res.append(a[pos])
		del a[pos]
		res_gcd = val
	return res

def get_ints():
	return [int(n) for n in input().split()]

def get_floats():
	return [float(n) for n in input().split()]

def seq2str(seq):
	return ' '.join((str(item) for item in seq))
zzz = get_ints()
assert len(zzz) == 1
t = zzz[0]
for i in range(t):
	zzz = get_ints()
	assert len(zzz) == 1
	n = zzz[0]
	zzz = get_ints()
	assert len(zzz) == n
	a = zzz
	res = calc(a)
	print(seq2str(res))


import math
for _ in range(int(input())):
	n = int(input())
	L = list(map(int, input().split()))
	m = max(L)
	ans = []
	ans.append(m)
	L.remove(m)
	while len(L) > 0:
		(g, e) = (-1, 0)
		for i in range(len(L)):
			if math.gcd(m, L[i]) > g:
				g = math.gcd(m, L[i])
				e = L[i]
		m = g
		L.remove(e)
		ans.append(e)
	print(*ans)


import math
for test in range(int(input())):
	pocet = int(input())
	vstup = list(map(int, input().split(' ')))
	maximum = max(vstup)
	output = str(maximum)
	b = []
	b.append(str(maximum))
	vstup.remove(max(vstup))
	maxgcd = int(b[0])
	while len(vstup) > 0:
		divisors = []
		for i in vstup:
			divisors.append(math.gcd(maxgcd, i))
		maxgcd = max(divisors)
		indices = [i for (i, x) in enumerate(divisors) if x == maxgcd]
		for i in indices:
			b.append(str(vstup[i]))
		indices.reverse()
		for i in indices:
			del vstup[i]
	print(' '.join(b))


from sys import stdin, stdout
input = stdin.readline
print = lambda x: stdout.write(str(x) + '\n')
from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [max(a)]
	taken = set(range(n))
	taken.remove(a.index(ans[0]))
	curr = ans[0]
	while len(ans) != n:
		mx = 0
		for i in taken:
			g = gcd(curr, a[i])
			if mx < g:
				mx = g
				idx = i
		curr = mx
		taken.remove(idx)
		ans.append(a[idx])
	ans = ' '.join(list(map(str, ans)))
	print(ans)


from math import *
from bisect import *
from collections import *
from random import *
from decimal import *

def inp():
	return int(input())

def st():
	return input().rstrip('\n')

def lis():
	return list(map(int, input().split()))

def ma():
	return list(map(int, input().split()))
t = inp()
while t:
	t -= 1
	n = inp()
	a = lis()
	cur = 0
	r = []
	while len(a) != 0:
		ind = 0
		mi = -1000000000000000
		for i in range(len(a)):
			if gcd(cur, a[i]) > mi:
				mi = gcd(cur, a[i])
				ind = i
		r.append(a[ind])
		cur = gcd(cur, a[ind])
		a.pop(ind)
	print(*r)


import math as mt
t = int(input())
for i in range(0, t):
	m = int(input())
	arr = list(map(int, input().strip().split()))[:m]
	l2 = []
	l3 = []
	y = max(arr)
	l2.append(y)
	l3.append(y)
	arr.remove(y)
	max1 = 0
	for jk in range(0, m - 1):
		max1 = 0
		for j in arr:
			gc = mt.gcd(l3[-1], j)
			if gc > max1:
				max1 = gc
				k = j
		l3.append(max1)
		l2.append(k)
		arr.remove(k)
	print(*l2, sep=' ')


(z, zz) = (input, lambda : list(map(int, z().split())))
zzz = lambda : [int(i) for i in stdin.readline().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
for _ in range(num):
	n = int(z())
	arr = zzz()
	arr = [(i, i) for i in arr]
	res = []
	while len(arr) > 0:
		arr.sort()
		x = arr.pop()
		res.append(x[1])
		for i in range(len(arr)):
			arr[i] = (gcd(arr[i][0], x[0]), arr[i][1])
	print(*res)


from collections import Counter
from math import gcd
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a, reverse=True)
	ans = [b[0]]
	maxa = b[0]
	try:
		maxi = max(b)
	except ValueError:
		pass
	b = b[1:]
	for k in range(n - 1):
		maxg = 1
		maxele = 0
		for j in range(len(b)):
			if gcd(b[j], maxi) >= maxg and b[j] <= maxa:
				maxg = gcd(maxi, b[j])
				maxele = b[j]
				o = j
		b[o] = 99999999
		maxi = maxg
		ans.append(maxele)
	for j in ans:
		print(j, end=' ')
	print('')


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	res = []
	egcd = 0
	i = 0
	maxgcd = 0
	while i < n:
		maxgcd = 0
		for j in range(n):
			if l[j] != -1:
				x = gcd(egcd, l[j])
				if maxgcd < x:
					loc = j
					maxgcd = x
		res.append(l[loc])
		l[loc] = -1
		egcd = maxgcd
		i = i + 1
	for i in res:
		print(i, end=' ')
	print()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr = [(e, e) for e in arr]
	res = []
	while len(arr) > 0:
		arr.sort()
		x = arr.pop()
		res.append(x[1])
		for i in range(len(arr)):
			arr[i] = (gcd(arr[i][0], x[0]), arr[i][1])
	print(*res)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	ans = [l[-1]]
	l.remove(l[-1])
	kk = 0
	tt = ans[0]
	while l:
		kk = 0
		for i in l:
			d = gcd(i, tt)
			if d >= kk:
				kk = d
				pp = i
		tt = kk
		l.remove(pp)
		ans.append(pp)
	print(*ans)


import sys
from collections import defaultdict as dd
from collections import deque
from functools import *
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations, product

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j):
	return 0 <= i < n and 0 <= j < n

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()
while t > 0:
	t -= 1
	n = fi()
	a = li()
	g = c = 0
	a.sort(reverse=True)
	i = 0
	k = a[0]
	while c < n:
		g = 0
		for j in range(n):
			if i == j or a[j] == 0:
				continue
			p = gcd(k, a[j])
			if p > g:
				g = p
				r = j
		c += 1
		print(a[i], end=' ')
		a[i] = 0
		k = g
		i = r
	print()


import os
import sys
import math
from io import BytesIO, IOBase
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().rstrip().split()))
	d = defaultdict(lambda : 0)
	for ele in a:
		d[ele] += 1
	maxNum = max(a)
	out = [maxNum] * d.pop(maxNum)
	currentGCD = maxNum
	while len(d) > 0 and currentGCD > 1:
		curMaxGCD = 0
		curMaxKey = -1
		for (key, value) in d.items():
			g = math.gcd(currentGCD, key)
			if g > curMaxGCD:
				curMaxGCD = g
				curMaxKey = key
		out.extend([curMaxKey] * d.pop(curMaxKey))
		currentGCD = curMaxGCD
	if len(d) > 0:
		for (key, value) in d.items():
			out.extend([key] * value)
	print(*out)


import math
ans = []
tests = int(input())
for i in range(tests):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	max_num = max(a)
	b = [max_num]
	a.remove(max_num)
	while a:
		deno_list = [math.gcd(a[x], max_num) for x in range(len(a))]
		max_deno = max(deno_list)
		index = deno_list.index(max_deno)
		max_num = max_deno
		b.append(a[index])
		a.remove(a[index])
	b = [str(x) for x in b]
	ans.append(b)
for i in ans:
	print(' '.join(i))


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	n = II()
	a = LI()
	a.sort(reverse=True)
	ans = [a.pop(0)]
	gcd = ans[0]
	for i in range(len(a)):
		m = 0
		ind = -1
		for j in range(len(a)):
			g = math.gcd(a[j], gcd)
			if g > m:
				m = g
				ind = j
		gcd = m
		ans.append(a.pop(ind))
	print(*ans)


from math import gcd
n = int(input())
for _ in range(n):
	f = int(input())
	ans = []
	l = list(map(int, input().split()))[:f]
	ans.append(max(l))
	cur = ans[-1]
	l.remove(ans[-1])
	while len(l) > 0:
		best = 0
		i = 0
		for j in l:
			if gcd(j, cur) > i:
				i = gcd(cur, j)
				best = j
		ans.append(best)
		l.remove(best)
		cur = i
	print(*ans)


from math import gcd
for v in [*open(0)][2::2]:
	l = list(map(int, v.split()))
	g = max(l)
	out = []
	while l:
		nex = max(((gcd(g, l[i]), i) for i in range(len(l))))
		out += [l.pop(nex[1])]
		g = nex[0]
	print(' '.join(map(str, out)))


import math
from decimal import *
import random
for _ in range(int(input())):
	n = int(input())
	arr = sorted(list(map(int, input().split())), reverse=True)
	ans = [str(arr[0])]
	pos = 0
	mrk = [0] * n
	mrk[0] = 1
	fin = False
	fnd = False
	mx = arr[0]
	while not fin:
		tmp = 1
		fnd = False
		for i in range(1, n):
			val = math.gcd(mx, arr[i])
			if val > tmp and mrk[i] == 0:
				pos = int(i)
				fnd = True
				tmp = int(val)
		if fnd:
			mrk[pos] = 1
			ans.append(str(arr[pos]))
			mx = int(tmp)
		else:
			fin = True
	for i in range(n):
		if mrk[i] == 0:
			ans.append(str(arr[i]))
	print(' '.join(ans))


import math
for _ in range(int(input())):
	x = int(input())
	arr = list(map(int, input().split()))
	mx = max(arr)
	out = [mx]
	arr.remove(mx)
	while arr:
		f = [math.gcd(arr[i], mx) for i in range(len(arr))]
		w = max(f)
		index = f.index(w)
		mx = w
		out.append(arr[index])
		arr.remove(arr[index])
	print(*out)


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	g = a[0]
	for j in range(1, n):
		maxg = 0
		maxi = j
		for i in range(j, n):
			x = math.gcd(g, a[i])
			if x > maxg:
				maxg = x
				maxi = i
		g = maxg
		(a[maxi], a[j]) = (a[j], a[maxi])
	for i in a:
		print(i, end=' ')
	print()


import math
for _ in range(int(input())):
	n = int(input())
	data = list(map(int, input().split()))
	gcd_value = 0
	for i in range(n):
		max_value = (0, 0)
		for j in range(n):
			if data[j] != -1:
				max_value = max(max_value, (math.gcd(gcd_value, data[j]), j))
		gcd_value = max_value[0]
		print(data[max_value[1]], end=' ')
		data[max_value[1]] = -1
	print()


from math import gcd
test = int(input())
for q in range(test):
	n = int(input())
	a = list(map(int, input().split()))
	m = 1000000000
	a.sort(reverse=True)
	x = []
	g = a[0]
	x.append(a[0])
	a[0] = 0
	N = n - 1
	flag = True
	while N > 0 and flag:
		cg = 0
		num = -1
		for i in range(n):
			if a[i] != 0 and gcd(a[i], g) > cg:
				cg = gcd(a[i], g)
				num = i
		x.append(a[num])
		g = cg
		a[num] = 0
		if g == 1:
			for i in range(n):
				if a[i] != 0:
					x.append(a[i])
				flag = False
		N -= 1
	for i in range(len(x)):
		if i < len(x) - 1:
			print(x[i], end=' ')
		else:
			print(x[i])


import math

def find_all_divisors_of_a_number(x):
	result = []
	for i in range(1, int(math.sqrt(x)) + 1):
		if x % i == 0:
			result.append(i)
			if i * i != x:
				result.append(x // i)
	return result
for _ in range(int(input())):
	n = int(input())
	data = list(map(int, input().split()))
	all_divisors = []
	all_divisors_set = []
	for i in range(n):
		all_divisors.append(sorted(find_all_divisors_of_a_number(data[i]), reverse=True))
		all_divisors_set.append(set(all_divisors[i]))
	visited = [False] * n
	maximum_index = -1
	maximum_value = -1
	for i in range(n):
		if data[i] > maximum_value:
			maximum_index = i
			maximum_value = data[i]
	print(maximum_value, end=' ')
	visited[maximum_index] = True
	now_set = all_divisors_set[maximum_index]
	for i in range(n - 1):
		now_index = -1
		now_value = -1
		for j in range(n):
			if visited[j]:
				continue
			for k in all_divisors[j]:
				if k in now_set:
					if k > now_value:
						now_value = k
						now_index = j
		maximum_index = now_index
		maximum_value = data[now_index]
		print(maximum_value, end=' ')
		visited[maximum_index] = True
		now_set = now_set & all_divisors_set[maximum_index]
	maximum = max(data)
	divisors = set()
	print()


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	gcd1 = [[] for i in range(10 ** 3 + 1)]
	a.sort(reverse=True)
	ans = 0
	if n == 2 or n == 1:
		print(*a)
		continue
	a1 = [a[0]]
	s = set()
	prevk = 0
	a1.append(0)
	s.add(0)
	prev = a[0]
	for i in range(n - 1):
		prevk = 0
		for j in range(n):
			if j not in s:
				k = gcd(prev, a[j])
				if k > prevk:
					prevk = k
					km = j
					a1[-1] = a[j]
		s.add(km)
		prev = prevk
		a1.append(0)
	print(*a1[:-1])


import math
for s in [*open(0)][2::2]:
	(*a,) = map(int, s.split())
	m = 0
	while a:
		(m, x) = max(((math.gcd(m, x), x) for x in a))
		print(x)
		a.remove(x)


import math
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = [int(_) for _ in input().split(' ')]
	ans = []
	a.sort()
	b = a[::-1]
	maxx_gcd = b[0]
	removed_indices = {}
	removed_indices[0] = True
	while len(removed_indices) < len(a):
		maxx_index = 0
		curr_gcd = maxx_gcd
		maxx_gcd = 1
		for (k, v) in enumerate(b):
			if k not in removed_indices:
				if math.gcd(v, curr_gcd) >= maxx_gcd:
					maxx_gcd = math.gcd(v, curr_gcd)
					maxx_index = k
		removed_indices[maxx_index] = True
	ans = []
	for x in removed_indices:
		ans.append(b[x])
	print(*ans)


from sys import stdin, stdout

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	x = list(map(int, stdin.readline().split()))
	x.sort(reverse=True)
	g = 0
	for i in range(n):
		maxi = 0
		ind = -1
		for j in range(n):
			if x[j] == -1:
				continue
			tmp = gcd(g, x[j])
			if tmp > maxi:
				ind = j
				maxi = tmp
		print(x[ind], end=' ')
		g = gcd(x[ind], g)
		x[ind] = -1
	print()


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	for _ in range(ii()):
		n = ii()
		a = li()
		f = [0] * (n + 5)
		a.sort(reverse=True)
		ans = [a[0]]
		f[0] = 1
		g = a[0]
		while len(ans) != n:
			mx = 0
			pos = -1
			for i in range(n):
				if f[i] == 0:
					if gcd(g, a[i]) > mx:
						mx = gcd(g, a[i])
						pos = i
			f[pos] = 1
			ans.append(a[pos])
			g = gcd(g, a[pos])
		print(*ans)
main()


def find_gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def gcd(l):
	num1 = l[0]
	num2 = l[1]
	gcd = find_gcd(num1, num2)
	for i in range(2, len(l)):
		gcd = find_gcd(gcd, l[i])
	return gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)[::-1]
	gcd = b[0]
	for i in range(1, n):
		value = 0
		swap = 1
		for j in range(i, n):
			temp = find_gcd(gcd, b[j])
			if temp > value:
				value = temp
				swap = j
		gcd = value
		(b[i], b[swap]) = (b[swap], b[i])
	print(*b)


from sys import stdin
from math import gcd
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(*a,) = map(int, input().split())
	g = max(a)
	a.remove(g)
	print(g, end=' ')
	for i in range(n - 1):
		x = mx = 0
		for j in a:
			if mx < gcd(g, j):
				mx = gcd(g, j)
				x = j
		a.remove(x)
		g = mx
		print(x, end=' ')
	print()


def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	x = max(a)
	ans = [x]
	for i in range(n):
		if a[i] == x:
			a.pop(i)
			break
	while len(a) != 0:
		n = len(a)
		m = 0
		for j in range(n):
			aa = gcd(x, a[j])
			if aa > m:
				ind = j
				m = aa
		ans.append(a[ind])
		x = gcd(x, a[ind])
		a.pop(ind)
	print(*ans)


def gcd(x, y):
	a = max(x, y)
	b = min(x, y)
	while a % b != 0:
		w = a % b
		a = b
		b = w
	return b

def ans(a, n):
	occupied = [0] * n
	gcds = []
	e = max(a)
	answer = [e]
	gcds.append(e)
	occupied[a.index(e)] = 1
	for i in range(1, n):
		temp = 0
		ind = -1
		for j in range(n):
			if gcd(gcds[-1], a[j]) > temp and occupied[j] == 0:
				temp = gcd(gcds[-1], a[j])
				ind = j
		occupied[ind] = 1
		answer.append(a[ind])
		gcds.append(temp)
	s = ''
	for i in answer:
		s = s + str(i) + ' '
	return s
m = int(input())
for i in range(m):
	n = int(input())
	arr = input().split()
	a = []
	for j in arr:
		a.append(int(j))
	print(ans(a, n))


for s in [*open(0)][2::2]:
	m = 0
	a = [0] * 4 ** 5
	s = s.split()
	for x in map(int, s):
		m = max(m, x)
		a[x] += 1
	b = c = [m]
	for _ in s:
		for m in c + b[::-1]:
			y = next((y for y in range(m, 4 ** 5, m) if a[y]), 0)
			if y:
				a[y] -= 1
				break
		print(y)
		b = []
		c = []
		i = 1
		while i * i <= m:
			if m % i < 1:
				b += (i,)
				c += (m // i,)
			i += 1


from math import gcd

def big_vova(arr):
	g = max(arr)
	ans = []
	while arr:
		nex = max(((gcd(g, arr[i]), i) for i in range(0, len(arr))))
		ans.append(arr.pop(nex[1]))
		g = nex[0]
	print(*ans)
	return ''
for i in range(int(input())):
	a = input()
	lst = list(map(int, input().strip().split()))
	print(big_vova(lst))


def gcd(x, y):
	return x if y == 0 else gcd(y, x % y)

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	print(max(a), end=' ')
	now = max(a)
	a.remove(now)
	while n > 1:
		x = -1
		select = a[0]
		for i in range(len(a)):
			if gcd(a[i], now) > x:
				x = gcd(a[i], now)
				select = a[i]
		now = gcd(now, select)
		print(select, end=' ')
		a.remove(select)
		n -= 1
	print()
ct = int(input())
while ct > 0:
	solve()
	ct -= 1


for _ in range(int(input())):
	from math import gcd
	n = int(input())
	a = list(map(int, input().split()))
	s = set()
	c = []
	a.sort()
	c.append(a[n - 1])
	s.add(n - 1)
	g = a[n - 1]
	for i in range(1, n):
		m = 0
		ind = -1
		temp = g
		for j in range(n):
			if j not in s and gcd(g, a[j]) >= m:
				ind = j
				m = gcd(g, a[j])
		s.add(ind)
		c.append(a[ind])
		g = gcd(g, a[ind])
	print(*c)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	output = list()
	max_gcd = 0
	while a:
		v = list(((gcd(max_gcd, x), x) for x in a))
		m = max(v)
		max_gcd = m[0]
		output.append(str(m[1]))
		a.remove(m[1])
	print(' '.join(output))


from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')
file = 1

def solve():
	prime = [1] * 1001
	(prime[0], prime[1]) = (0, 0)
	for i in range(2, 1001):
		if prime[i]:
			for j in range(i * i, 1001, i):
				prime[j] = 0
	for _ in range(ii()):
		n = ii()
		a = li()
		mx = max(a)
		ans = []
		m = [0] * n
		while 1:
			ind = -1
			mx1 = 0
			for j in range(n):
				if m[j] == 1:
					continue
				x1 = gcd(mx, a[j])
				if x1 > mx1:
					mx1 = x1
					ind = j
			if ind != -1:
				ans.append(a[ind])
				m[ind] = 1
			mx = mx1
			if mx1 <= 1:
				break
		for i in range(n):
			if m[i] == 0:
				ans.append(a[i])
		print(*ans)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


import sys, math as mt
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
sv = [0] * 1002
pr = []
for i in range(2, len(sv)):
	if sv[i] == 0:
		sv[i] = i
		pr.append(i)
		for j in range(2 * i, len(sv), i):
			sv[j] = i

def div(n):
	dv = []
	i = 0
	while pr[i] <= int(n ** 0.5):
		if n % pr[i] == 0:
			dv.append(pr[i])
		i += 1
	return dv
(t,) = I()
for _ in range(t):
	(n,) = I()
	l = I()
	x = max(l)
	l = sorted(l, reverse=True)
	an = [x]
	l.remove(x)
	while l:
		gd = 0
		el = 1
		for k in l:
			if mt.gcd(k, x) > gd:
				gd = mt.gcd(k, x)
				el = k
		x = gd
		an.append(el)
		l.remove(el)
	print(*an)


import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	arr = []
	arr.append(l[0])
	res = l[0]
	for i in range(1, n):
		mx = -1000000
		idx = -1
		for j in range(1, n):
			if l[j] != -1:
				ans = math.gcd(res, l[j])
				if ans > mx:
					mx = ans
					idx = j
		res = math.gcd(res, l[idx])
		arr.append(l[idx])
		l[idx] = -1
	print(*arr)


import math
ct = input()
for line in range(int(ct)):
	n = input()
	arr = [int(i) for i in input().split()]
	final = []
	final.append(max(arr))
	arr.remove(max(arr))
	gcdCurrent = final[0]
	while len(arr) > 0:
		for i in range(len(arr)):
			test = [math.gcd(gcdCurrent, arr[i]) for i in range(len(arr))]
			final.append(arr[test.index(max(test))])
			gcdCurrent = math.gcd(gcdCurrent, max(test))
			arr.remove(arr[test.index(max(test))])
	final = [str(i) for i in final]
	print(' '.join(final))


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [max(a)]
	a.remove(ans[0])
	n -= 1
	gcdu = ans[0]
	while n > 0:
		m = 1
		mi = 0
		for i in range(n):
			k = math.gcd(gcdu, a[i])
			if k > m:
				m = k
				mi = i
		gcdu = m
		ans.append(a[mi])
		a.remove(a[mi])
		n -= 1
	print(*ans)


import sys
import math as mt
import collections as cc
import sys
import itertools as it
I = lambda : list(map(int, input().split()))
input = sys.stdin.readline
for tc in range(int(input())):
	(n,) = I()
	l = I()
	ma = max(l)
	if 1:
		ev = l
		ans = [ma]
		ev.remove(ma)
		now = ma
		while ev:
			temp = now
			te = -1
			ele = -1
			for j in ev:
				if mt.gcd(j, temp) > te:
					te = mt.gcd(j, temp)
					ele = j
			now = te
			ans.append(ele)
			ev.remove(ele)
		print(*ans)


def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for _ in range(ii()):
	n = ii()
	a = li()
	f = [0] * (n + 5)
	a.sort(reverse=True)
	ans = [a[0]]
	f[0] = 1
	g = a[0]
	while len(ans) != n:
		mx = 0
		pos = -1
		for i in range(n):
			if f[i] == 0:
				if gcd(g, a[i]) > mx:
					mx = gcd(g, a[i])
					pos = i
		f[pos] = 1
		ans.append(a[pos])
		g = gcd(g, a[pos])
	print(*ans)


import os
from io import BytesIO, IOBase
import sys
from math import *
from collections import Counter

def main():
	for t in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		c = max(a)
		f = Counter(a)
		d = [c]
		e = Counter()
		e[c] += 1
		temp = c
		for i in range(n - 1):
			ma = 0
			val = 0
			for j in range(n):
				if e[a[j]] < f[a[j]]:
					z = gcd(temp, a[j])
					if ma < z:
						ma = z
						val = a[j]
			e[val] += 1
			temp = gcd(temp, val)
			d.append(val)
		print(*d)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import math

def answer(n, A):
	A.sort()
	vis = [0] * n
	arr = [A[n - 1]]
	vis[n - 1] = 1
	g = A[n - 1]
	while len(arr) < n:
		index = -1
		maxi = 0
		for i in range(n):
			if vis[i] == 0:
				x = math.gcd(g, A[i])
				if x > maxi:
					maxi = x
					index = i
		if maxi > 1:
			vis[index] = 1
			arr.append(A[index])
			g = maxi
		else:
			break
	for i in range(n):
		if vis[i] == 0:
			arr.append(A[i])
	return arr
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	b = answer(n, arr)
	print(*b)


import math
for i in range(int(input())):
	n = int(input())
	ls = [int(a) for a in input().split()]
	ls1 = []
	ls1.append(max(ls))
	ls.remove(max(ls))
	an = 0
	for j in range(n - 1):
		if math.gcd(ls1[0], ls[j]) > an:
			an = math.gcd(ls1[0], ls[j])
			an1 = ls[j]
	if n > 1:
		ls1.append(an1)
		ls.remove(an1)
		cgcd = an
	for j in range(n - 2):
		an = 0
		for k in range(len(ls)):
			if math.gcd(cgcd, ls[k]) > an:
				an = math.gcd(cgcd, ls[k])
				an1 = ls[k]
		ls.remove(an1)
		ls1.append(an1)
		cgcd = an
	print(''.join((str(a) + ' ' for a in ls1)))


import os
import sys
from io import BytesIO, IOBase
import threading
from collections import defaultdict, Counter
from math import gcd

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	pg = max(arr)
	ans = []
	for i in range(n):
		t = 1
		tel = -1
		for el in arr:
			gr = gcd(el, pg)
			if gr >= t:
				tel = el
				t = gr
		arr.remove(tel)
		ans.append(tel)
		pg = t
	print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(int(input())):
	main()


import math
import sys
input = sys.stdin.readline
T = int(input())
for t in range(T):
	N = int(input())
	A = [int(_) for _ in input().split()]
	if N == 1:
		print(A[0])
		continue
	maxel = -1
	maxi = -1
	for (i, el) in enumerate(A):
		if el > maxel:
			maxel = el
			maxi = i
	inds = set()
	for i in range(N):
		if i != maxi:
			inds.add(i)
	res = [maxel]
	current_gcd = maxel
	for i in range(N - 1):
		current_max = -1
		best_ind = -1
		for ind in inds:
			current = math.gcd(A[ind], current_gcd)
			if current > current_max:
				current_max = current
				best_ind = ind
		inds.remove(best_ind)
		res.append(A[best_ind])
		current_gcd = current_max
	print(' '.join(map(str, res)))


from math import gcd
t = int(input())
for i in range(t):
	n = int(input())
	string = input()
	numbers = string.split()
	visited = [False] * n
	maximum = 0
	for j in range(n):
		if int(numbers[j]) > maximum:
			index = j
			maximum = int(numbers[j])
	visited[index] = True
	value = maximum
	print(maximum, end=' ')
	for k in range(1, n):
		maximum = 0
		for j in range(n):
			if not visited[j] and gcd(int(numbers[j]), value) > maximum:
				index = j
				maximum = gcd(int(numbers[j]), value)
		visited[index] = True
		value = maximum
		print(int(numbers[index]), end=' ')


from math import gcd
for t in range(int(input())):
	n = int(input())
	a = dict()
	for i in map(int, input().split()):
		if i in a:
			a[i] += 1
		else:
			a[i] = 1
	gcd_prev = max(a)
	b = [gcd_prev] * a[gcd_prev]
	del a[gcd_prev]
	while gcd_prev != 1:
		max_gcd = max([gcd(i, gcd_prev) for i in a] + [1])
		for i in list(a):
			if not i % max_gcd:
				b += [i] * a[i]
				del a[i]
		gcd_prev = max_gcd
	for i in list(a):
		b += [i] * a[i]
		del a[i]
	print(*b)


import math
for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	m = max(arr)
	arr.remove(m)
	gcd = m
	res = [m]
	num = 0
	while len(arr) > 0:
		tem = 0
		for i in range(len(arr)):
			if math.gcd(gcd, arr[i]) > tem:
				tem = math.gcd(gcd, arr[i])
				num = i
		res.append(arr[num])
		gcd = tem
		del arr[num]
	print(*res)


def hcfnaive(a, b):
	if b == 0:
		return a
	else:
		return hcfnaive(b, a % b)
for _ in range(int(input())):
	c = int(input())
	a = list(map(int, input().split()))
	b = a
	b.sort()
	ans = []
	ans.append(b[c - 1])
	curr_gcd = b[c - 1]
	b.pop(c - 1)
	while len(ans) != c:
		fgcd = -1
		for i in range(len(b)):
			poi = hcfnaive(curr_gcd, b[i])
			if poi > fgcd:
				fgcd = poi
				high = i
		ans.append(b[high])
		b.pop(high)
		curr_gcd = fgcd
	for elem in ans:
		print(elem, end=' ')


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	b = a[0:1]
	g = b[0]
	a = a[1:]
	while a:
		q = max(a, key=lambda x: gcd(x, g))
		g = gcd(q, g)
		a.remove(q)
		b.append(q)
	print(' '.join((str(x) for x in b)))


import math
t = int(input())
ans = []

def solve(n, arr):
	ans = [max(arr)]
	gcd = max(arr)
	arr.remove(max(arr))
	while arr != []:
		gcds = []
		for ele in arr:
			gcds.append(math.gcd(ele, gcd))
		gcd = max(gcds)
		element_index = gcds.index(max(gcds))
		ans.append(arr[element_index])
		arr.remove(arr[element_index])
	return ans
	pass
for i in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	ans.append(solve(n, arr))
for test in ans:
	for ele in test:
		print(ele, end=' ')
	print()


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	b = [1] * n
	b[0] = a[0]
	for i in range(1, n):
		for j in range(i, n):
			t = math.gcd(b[i - 1], a[j])
			if t > b[i]:
				b[i] = t
				(a[i], a[j]) = (a[j], a[i])
	print(*a)


import math
from sys import stdin, stdout
inp = stdin.readline
out = stdout.write

def mi():
	return map(int, inp().split())

def li():
	return list(mi())

def ii():
	return int(inp())

def main():
	for _ in range(ii()):
		n = ii()
		a = li()
		ans = []
		ans.append(max(a))
		a.remove(max(a))
		ggcd = ans[0]
		for _ in range(n - 1):
			m = -float('inf')
			v = None
			for i in a:
				temp = math.gcd(ggcd, i)
				if temp > m:
					m = temp
					v = i
			ans.append(v)
			a.remove(v)
			ggcd = math.gcd(ggcd, v)
		print(*ans)
main()


import sys
from math import ceil, gcd
from collections import deque
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort(reverse=True)
	b = []
	g = a[0]
	b.append(a[0])
	a.pop(0)
	mx = 1
	nx = 0
	while a:
		mx = 1
		nx = 0
		for i in range(len(a)):
			if gcd(g, a[i]) >= mx:
				mx = gcd(g, a[i])
				nx = i
		g = gcd(g, mx)
		b.append(a[nx])
		a.pop(nx)
	for i in b:
		print(i, end=' ')
	print()


import math
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	max111 = max(a)
	ans = list()
	for j in range(n):
		if max111 == 1:
			break
		besg = math.gcd(max111, a[0])
		mark = 0
		while False:
			break
		for k in range(n):
			if math.gcd(max111, a[k]) > besg:
				besg = math.gcd(max111, a[k])
				mark = k
		ans.append(a[mark])
		a[mark] = -1
		max111 = besg
	for j in a:
		if j != -1:
			ans.append(j)
	xx = 0
	for cc in ans:
		if cc == -1:
			continue
		print(cc, end=' ')
	print('')


import sys
input = sys.stdin.buffer.readline
from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = [int(c) for c in input().split()]
	mx = max(arr)
	mxind = max(range(len(arr)), key=lambda x: arr[x])
	ans = [mx]
	arr[mxind] = None
	for i in range(n - 1):
		currmx = 0
		for j in range(len(arr)):
			if arr[j] is None:
				continue
			gc = gcd(mx, arr[j])
			if gc > currmx:
				currmx = gc
				mxind = j
		ans.append(arr[mxind])
		mx = currmx
		arr[mxind] = None
	print(*ans)


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
from functools import lru_cache
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(mapi())
	a.sort(reverse=True)
	res = [a[0]]
	gc = a[0]
	a[0] = -1
	for i in range(n - 1):
		mx = 0
		idx = -1
		for j in range(n):
			if a[j] != -1 and gcd(a[j], gc) > mx:
				mx = gcd(a[j], gc)
				idx = j
		res.append(a[idx])
		gc = mx
		a[idx] = -1
	print(*res)


T = int(input())

def prime(n):
	for i in range(2, 2 + int(n ** 0.5)):
		if n % i == 0:
			return 0
	return 1

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a
for t in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	d = False
	a.sort()
	used = [0] * n
	cg = a[n - 1]
	cgi = n - 1
	for i in range(n):
		used[cgi] = 1
		print(a[cgi], end=' ')
		ccg = 1
		for j in range(n):
			if not used[j]:
				if gcd(cg, a[j]) >= ccg:
					ccg = gcd(cg, a[j])
					cgi = j
		cg = ccg
	print()


import sys

def input():
	return sys.stdin.readline()[:-1]

def getInt():
	return int(input())

def getIntIter():
	return map(int, input().split())

def getIntList():
	return list(getIntIter())

def flush():
	sys.stdout.flush()

def gcd(a, b):
	if b > a:
		(a, b) = (b, a)
	while b != 0:
		(a, b) = (b, a % b)
	return a
for _ in range(getInt()):
	n = getInt()
	nums = getIntList()
	nums.sort()
	out = [nums[-1]]
	currGcd = nums[-1]
	del nums[-1]
	while len(nums) > 0:
		gcdMap = list(map(lambda x: gcd(currGcd, x), nums))
		if max(gcdMap) == 1:
			out.extend(nums)
			break
		i = gcdMap.index(max(gcdMap))
		out.append(nums[i])
		currGcd = gcd(currGcd, nums[i])
		del nums[i]
	print(' '.join(map(str, out)))


from math import gcd
R = lambda : map(int, input().split())
(t,) = R()
for _ in range(t):
	n = int(input())
	arr = list(R())
	ans = []
	ci = max(arr)
	while arr:
		curr = max(((gcd(ci, val), val) for val in arr))
		arr.remove(curr[1])
		ans.append(curr[1])
		ci = curr[0]
	print(*ans)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	maxi = max(arr)
	ans = [maxi]
	arr.remove(maxi)
	g = maxi
	while arr:
		max_gcd = 0
		val = -1
		for ele in arr:
			if gcd(ele, g) > max_gcd:
				max_gcd = gcd(ele, g)
				val = ele
		ans.append(val)
		arr.remove(val)
		g = max_gcd
	print(*ans)


from math import gcd
for _ in range(int(input())):
	lens = int(input())
	arrs = [int(x) for x in input().split()]
	B = []
	g = 0
	while arrs:
		a = max(arrs, key=lambda a: gcd(a, g))
		B.append(a)
		g = gcd(a, g)
		arrs.remove(a)
	print(*B)


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().strip().split()))
	if n == 1:
		print(*a)
	else:
		b = []
		k = max(a)
		b.append(k)
		a.remove(k)
		while a:
			f = -10 ** 9
			m = 0
			for z in a:
				temp = math.gcd(k, z)
				if temp > f:
					f = temp
					m = z
			k = f
			b.append(m)
			a.remove(m)
		print(*b)


from math import gcd

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		checkAngela = [1] * n
		m = max(a)
		ans = []
		ans.append(m)
		checkAngela[a.index(m)] = 0
		currwhite = ans[0]
		length = 1
		while 1:
			if length == n:
				break
			ind = -1
			temp = 0
			for i in range(n):
				if checkAngela[i]:
					if gcd(currwhite, a[i]) > temp:
						temp = gcd(currwhite, a[i])
						ind = i
			if ind != -1:
				ans.append(a[ind])
				checkAngela[ind] = 0
				length += 1
				currwhite = gcd(currwhite, a[ind])
		print(*ans)
main()


from __future__ import division, print_function
import sys
sys.setrecursionlimit(10 ** 4)
from sys import stdin, stdout
import bisect
import math
import heapq
i_m = 9223372036854775807

def modinv(n, p):
	return pow(n, p - 2, p)

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
import math

def GCD(x, y):
	x = abs(x)
	y = abs(y)
	if min(x, y) == 0:
		return max(x, y)
	while y:
		(x, y) = (y, x % y)
	return x

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l
prime = []

def SieveOfEratosthenes(n):
	global prime
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	f = []
	for p in range(2, n):
		if prime[p]:
			f.append(p)
	return f

def primeFactors(n):
	a = []
	while n % 2 == 0:
		a.append(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			a.append(i)
			n = n // i
	if n > 2:
		a.append(n)
	return a

def main():
	t = inin()
	for _ in range(t):
		n = inin()
		a = ain()
		b = []
		x = max(a)
		b.append(x)
		a.remove(x)
		while len(a) > 0:
			n = len(a)
			p = 0
			q = 0
			a.sort()
			for i in a:
				if GCD(x, i) > p:
					p = GCD(x, i)
					q = i
			x = p
			a.remove(q)
			b.append(q)
		print(*b)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'R'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'R'[0]:
		A.append(sign * numb)
	return A
main()


from math import gcd
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	al = list(map(int, input().split()))
	al.sort(reverse=True)
	first = al[0]
	c_gcd = first
	ans = [first]
	used = [False] * n
	used[0] = True
	for _ in range(n - 1):
		a = 0
		v = 0
		vi = -1
		for i in range(1, n):
			if used[i]:
				continue
			curr_v = gcd(c_gcd, al[i])
			if curr_v > v:
				v = curr_v
				vi = i
				a = al[i]
			elif curr_v == v and a > al[i]:
				v = curr_v
				vi = i
				a = al[i]
		ans.append(a)
		used[vi] = True
		c_gcd = v
	print(*ans)


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	c = [a[-1]]
	b = [0] * n
	b[-1] = 1
	d = 1
	g = c[0]
	while d != n:
		m = 0
		ind = -1
		for i in range(n):
			if b[i] == 0:
				k = math.gcd(g, a[i])
				if k > m:
					m = k
					ind = i
		c += [a[ind]]
		b[ind] = 1
		d += 1
		g = m
	print(*c)


def gcd(x, y):
	if y == 0:
		return x
	return gcd(y, x % y)
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	c = []
	g = m = ij = f = te = 0
	ind = [j for j in range(n)]
	for j in range(n):
		m = 0
		for k in ind:
			(maxi, mini) = (max(a[k], g), min(a[k], g))
			te = gcd(maxi, mini)
			if te > m:
				m = te
				ij = k
		g = m
		ind.remove(ij)
		c.append(a[ij])
		if g == 1:
			break
	for j in ind:
		c.append(a[j])
	for j in c:
		print(j, end=' ')
	print()


import math
t = int(input())
while t > 0:
	n = int(input())
	a = list(map(int, input().split()))
	ans = [max(a)]
	curr_gcd = ans[0]
	while len(ans) < n:
		prev = ans[-1]
		next = -1
		temp_gcd = -float('inf')
		a.remove(prev)
		for item in a:
			if math.gcd(item, curr_gcd) > temp_gcd:
				temp_gcd = math.gcd(item, curr_gcd)
				next = item
		curr_gcd = temp_gcd
		ans.append(next)
	print(*ans)
	t -= 1


from math import gcd
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	answer = []
	answer.append(a.pop(0))
	n -= 1
	gc = answer[0]
	for _ in range(n):
		index = 0
		m = 0
		for (i, val) in enumerate(a):
			num = gcd(gc, val)
			if num >= m:
				m = num
				index = i
		gc = min(gc, m)
		if gc == 1:
			answer.extend(a)
			break
		else:
			answer.append(a.pop(index))
	print(' '.join((str(num) for num in answer)))


import math
test = int(input())
for _ in range(test):
	num = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	mgcd = arr.pop()
	arr.reverse()
	ans = [mgcd]
	for i in range(num - 1):
		maxi = 1
		for j in range(len(arr)):
			g = math.gcd(mgcd, arr[j])
			maxi = max(g, maxi)
			if maxi == g:
				mi = j
		mgcd = maxi
		ans.append(arr[mi])
		arr.pop(mi)
	print(*ans)


def gcd(a, b):
	if a % b == 0:
		return b
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = {}
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	s = list(d.keys())
	x = [max(s)]
	s.remove(x[0])
	cgcd = x[0]
	while len(s):
		temp = 0
		ans = None
		for i in s:
			if gcd(cgcd, i) > temp:
				temp = gcd(cgcd, i)
				ans = i
		cgcd = temp
		x.append(ans)
		s.remove(ans)
	for i in x:
		print(*[i] * d[i], end=' ')
	print()


import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

def solve(lst):
	console('----- solving ------')
	taken = [False for _ in lst]
	res = [-1 for _ in lst]
	maxidx = lst.index(max(lst))
	res[0] = lst[maxidx]
	taken[maxidx] = True
	pergcd = lst[maxidx]
	console(taken)
	for (i, _) in enumerate(lst[1:], start=1):
		curmax = -1
		idx = -1
		for (j, y) in enumerate(lst):
			if taken[j]:
				continue
			val = math.gcd(pergcd, y)
			if val > curmax:
				curmax = val
				idx = j
		pergcd = curmax
		res[i] = lst[idx]
		taken[idx] = True
	return res

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
for case_num in range(int(input())):
	_ = int(input())
	lst = list(map(int, input().split()))
	res = solve(lst)
	print(' '.join((str(x) for x in res)))


import sys
input = sys.stdin.readline
from math import gcd
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	NOW = 0
	ANS = []
	while A:
		MAX = -1
		NEXT = -1
		NEXTIND = -1
		for i in range(len(A)):
			a = A[i]
			if gcd(NOW, a) > MAX:
				MAX = gcd(NOW, a)
				NEXT = a
				NEXTIND = i
		if MAX != 1:
			ANS.append(NEXT)
			A.pop(NEXTIND)
			NOW = gcd(NOW, NEXT)
		else:
			ANS += A
			break
	print(*ANS)


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	b = []
	b.append(a[0])
	g = a[0]
	visited = set()
	visited.add(0)
	while True:
		if len(b) == n:
			break
		best = 0
		best_idx = 0
		for j in range(1, n):
			if j in visited:
				continue
			if best < gcd(a[j], g):
				best = gcd(a[j], g)
				best_idx = j
		b.append(a[best_idx])
		g = best
		visited.add(best_idx)
	print(*b)


import math
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = [max(a)]
	gcd = max(a)
	a.remove(max(a))
	while len(a) > 0:
		t = 0
		var = 0
		for i in a:
			if math.gcd(gcd, i) > t:
				var = i
				t = math.gcd(gcd, i)
		ans.append(var)
		a.remove(var)
		gcd = t
	print(*ans)


import sys
import math, bisect
sys.setrecursionlimit(10 ** 5)
from collections import defaultdict
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, OrderedDict

def I():
	return int(sys.stdin.readline())

def neo():
	return map(int, sys.stdin.readline().split())

def Neo():
	return list(map(int, sys.stdin.readline().split()))
for _ in range(I()):
	N = I()
	A = Neo()
	A.sort()
	gcd = A[-1]
	A = A[:-1]
	Ans = [gcd]
	while len(A) > 0:
		(p, q) = (0, 0)
		for i in A:
			if math.gcd(i, gcd) > p:
				p = math.gcd(i, gcd)
				q = i
		gcd = math.gcd(gcd, p)
		Ans.append(q)
		A.remove(q)
	print(*Ans)


import math
from collections import deque
from sys import stdin, stdout
from string import ascii_letters
import sys
letters = ascii_letters
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = sorted(list(map(int, input().split())))
	taken = [0] * n
	res = [arr[-1]]
	taken[-1] = 1
	arr.pop(-1)
	last = res[0]
	for i in range(n - 1):
		mx = 0
		ind = 0
		for g in range(n):
			if taken[g]:
				continue
			bf = math.gcd(arr[g], last)
			if bf > mx:
				mx = bf
				ind = g
		res.append(arr[ind])
		taken[ind] = 1
		last = mx
	print(*res)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	ans = [arr[0]]
	tmp = arr[0]
	arr.pop(0)
	n -= 1
	while n > 0:
		maxx = 0
		item = 0
		for i in arr:
			if gcd(tmp, i) >= maxx:
				maxx = gcd(tmp, i)
				item = i
		tmp = maxx
		arr.remove(item)
		n -= 1
		ans.append(item)
	print(*ans)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)
	ans = [a[-1]]
	check = a[-1]
	del a[-1]
	while a:
		mx = -11111
		for i in range(len(a)):
			if mx <= gcd(check, a[i]):
				mx = gcd(check, a[i])
				store = i
		ans.append(a[store])
		del a[store]
		check = mx
	print(*ans)


from functools import reduce
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a
for _ in range(inn()):
	n = inn()
	a = arr()
	a.sort(reverse=True)
	ans = []
	ans += [a[0]]
	l = []
	for i in range(1, n):
		res = gcd(a[0], a[i])
		if res > 1:
			l += [a[i]]
			a[i] = -1
	if len(l) == 0:
		print(*a)
		continue
	res = a[0]
	for i in range(len(l)):
		mx = -1
		digit = -1
		id = -1
		for j in range(len(l)):
			if l[j] != -1:
				val = gcd(res, l[j])
				if val > mx:
					mx = val
					digit = l[j]
					id = j
		if mx != -1:
			ans += [digit]
			res = mx
			l[id] = -1
	a[0] = -1
	for i in range(len(l)):
		if l[i] != -1:
			ans += [l[i]]
	for i in range(n):
		if a[i] != -1:
			ans += [a[i]]
	print(*ans)


def gcd(a, b):
	while a * b:
		a %= b
		(a, b) = (b, a)
	return a
for _ in range(int(input())):
	n = int(input())
	lis = sorted(map(int, input().split()), reverse=True)
	prev = lis[0]
	for i in range(1, n):
		tmp = ind = 0
		for j in range(i, n):
			t = gcd(prev, lis[j])
			if t > tmp:
				tmp = t
				ind = j
		prev = tmp
		(lis[ind], lis[i]) = (lis[i], lis[ind])
	print(*lis)


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	g = 0
	b = []
	for _ in range(n):
		x = max((gcd(y, g) for y in a if y > 0))
		i = next((i for i in range(n) if a[i] > 0 and gcd(g, a[i]) == x))
		b.append(a[i])
		a[i] = 0
		g = x
	print(*b)


import math
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a, reverse=True)
	p = -1
	g = a[0]
	j = 1
	while j < n:
		q = 0
		for i in range(j, n):
			y = math.gcd(g, a[i])
			if y > q:
				q = y
				p = i
		(a[j], a[p]) = (a[p], a[j])
		g = q
		j += 1
	print(*a)


t = int(input())
for i in range(t):
	import math
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	a.sort()
	b.append(a[n - 1])
	a[n - 1] = -1
	ma = -9999999999
	abg = b[-1]
	for i in range(1, len(a)):
		ma = -9999999999
		k = 0
		for j in range(len(a)):
			if a[j] != -1:
				if math.gcd(a[j], abg) > ma:
					k = j
					ma = math.gcd(a[j], abg)
		b.append(a[k])
		abg = math.gcd(a[k], abg)
		a[k] = -1
	print(*b)


import math
T = int(input())
for _ in range(T):
	n = int(input())
	x = list(map(int, input().split()))
	l = list()
	gcd = 0
	vis = [-1 for k in range(n)]
	for i in range(len(x)):
		ind = 0
		maxi = 0
		for j in range(len(x)):
			if vis[j] != 1 and math.gcd(gcd, x[j]) > maxi:
				maxi = math.gcd(gcd, x[j])
				ind = j
		gcd = maxi
		vis[ind] = 1
		l.append(x[ind])
	st = ''
	for i in l:
		st += str(i) + ' '
	print(st)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	mx = 0
	id1 = 0
	mx1 = 0
	id2 = 0
	mat = [[0] * n] * n
	for i in range(n):
		if ar[i] > mx1:
			mx1 = ar[i]
			id2 = i
	dic = {}
	dic[id2] = 1
	s = ''
	s += str(ar[id2]) + ' '
	gc = ar[id2]
	while len(dic) < n:
		for i in range(n):
			if dic.get(i) == None and gcd(gc, ar[i]) > mx:
				mx = gcd(gc, ar[i])
				id1 = i
		s += str(ar[id1]) + ' '
		gc = gcd(gc, ar[id1])
		id2 = id1
		mx = 0
		dic[id2] = 1
	print(s)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	fl = [0] * n
	g = max(a)
	b = [g]
	fl[a.index(g)] = 1
	for i in range(1, n):
		cur = -1
		for j in range(n):
			if fl[j]:
				continue
			cur = max(cur, gcd(g, a[j]))
		for j in range(n):
			if fl[j]:
				continue
			if cur == gcd(g, a[j]):
				fl[j] = 1
				g = cur
				b.append(a[j])
				break
	print(*b)


from sys import stdin
import sys
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
from sys import setrecursionlimit
import threading

def main():

	def gcd(a, b):
		if b == 0:
			return a
		return gcd(b, a % b)
	(t,) = gil()
	for _ in range(t):
		(n,) = gil()
		a = gil()
		a.sort()
		vis = [0] * n
		vis[-1] = 1
		ans = [a.pop()]
		cgcd = ans[0]
		for i in range(1, n):
			new = [0, 0]
			for j in range(n):
				if vis[j] == 0:
					newGcd = gcd(a[j], cgcd)
					if newGcd > new[0]:
						new = [newGcd, j]
			cgcd = new[0]
			j = new[-1]
			vis[j] = 1
			ans.append(a[j])
		for v in ans:
			print(v, end=' ')
		print()
setrecursionlimit(10000)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	maxi = max(l)
	ans = []
	while l:
		temp = max(((gcd(maxi, l[i]), i) for i in range(len(l))))
		ans.append(l.pop(temp[1]))
		maxi = temp[0]
	print(' '.join(map(str, ans)))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	s = map(int, input().split())
	s = list(s)
	g = max(s)
	ans = []
	while len(s) != 0:
		MAX = 0
		for x in s:
			tmp = gcd(g, x)
			if tmp > MAX:
				MAX = tmp
				candidate = x
		g = MAX
		ans.append(candidate)
		s.remove(candidate)
	print(*ans)


def read(datatype=int):
	return datatype(input())

def readl(datatype=int):
	return list(map(datatype, input().split()))

def printl(data):
	string = ''
	for d in data:
		string += str(d) + ' '
	print(string)

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def best_gcd(old, arr, used_arr):
	index = 0
	max_gcd = 0
	for i in range(len(arr)):
		this_gcd = gcd(old, arr[i])
		if this_gcd >= max_gcd and (not used_arr[i]):
			max_gcd = this_gcd
			index = i
	return (max_gcd, index)

def testcase():
	n = read()
	arr = readl()
	used_arr = [False for _ in arr]
	max_index = 0
	for i in range(1, n):
		if arr[i] > arr[max_index]:
			max_index = i
	used_arr[max_index] = True
	brr = [arr[max_index]]
	crr = [arr[max_index]]
	for _ in range(n - 1):
		(max_gcd, index) = best_gcd(crr[-1], arr, used_arr)
		brr.append(arr[index])
		crr.append(max_gcd)
		used_arr[index] = True
	printl(brr)
	return
t = read()
for _ in range(t):
	testcase()


import sys
input = sys.stdin.readline
from math import gcd
t = int(input())
for i in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	ANS = [max(A)]
	A.pop(A.index(max(A)))
	g = ANS[0]
	for j in range(n - 1):
		mg = 0
		mind = -1
		for k in range(len(A)):
			ng = gcd(g, A[k])
			if ng > mg:
				mg = ng
				mind = k
		ANS.append(A[mind])
		A.pop(mind)
		g = mg
	print(*ANS)


import math
for i in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	l.sort(reverse=True)
	a = max(l)
	l.remove(a)
	p = []
	q = []
	q.append(a)
	p.append(a)
	for k in range(n):
		b = []
		for j in l:
			b.append(math.gcd(q[k], j))
		if len(l) > 0:
			t = max(b)
			q.append(t)
			w = b.index(t)
			p.append(l[w])
			l.remove(l[w])
	print(*p)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
import math
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gift():
	for _ in range(t):
		n = int(input())
		arry = list(map(int, input().split()))
		arry.sort(reverse=True)
		start = arry[0]
		ans = [start]
		lst = sorted(list(factors(start)), reverse=True)
		index = 1
		arry.remove(start)
		gcd = lst
		while index <= n - 1:
			found = False
			for ele in gcd:
				for aryelement in arry:
					if aryelement % ele == 0:
						found = True
						toremove = aryelement
						break
				if found:
					break
			ans.append(toremove)
			arry.remove(toremove)
			newlst = sorted(list(factors(toremove)), reverse=True)
			newgcd = []
			for divisor in newlst:
				if divisor in gcd:
					newgcd.append(divisor)
			gcd = newgcd
			index += 1
		yield ' '.join((str(x) for x in ans))
t = int(input())
ans = gift()
print(*ans, sep='\n')


import math
for i in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	res = []
	res.append(max(l))
	l.remove(max(l))
	ind = 0
	gcdvalue = res[ind]
	while len(res) != n:
		mv = 0
		for i in range(len(l)):
			temp = math.gcd(gcdvalue, l[i])
			if temp > mv:
				mv = temp
				value = l[i]
		gcdvalue = mv
		res.append(value)
		ind += 1
		l.remove(value)
	print(*res)


import math
T = int(input())
for t in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	maxind = 0
	oldmaxgcd = a[0]
	for i in range(1, n):
		if a[i] > oldmaxgcd:
			maxind = i
			oldmaxgcd = a[i]
	print(a[maxind], end=' ')
	del a[maxind]
	n -= 1
	while a:
		maxind = 0
		maxgcd = math.gcd(oldmaxgcd, a[0])
		for i in range(1, n):
			gcd = math.gcd(oldmaxgcd, a[i])
			if gcd > maxgcd:
				maxind = i
				maxgcd = gcd
		print(a[maxind], end=' ')
		del a[maxind]
		n -= 1
		oldmaxgcd = maxgcd
	print()


import sys
input = sys.stdin.readline
from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	g = max(l)
	out = []
	while l:
		nex = max(((gcd(g, l[i]), i) for i in range(len(l))))
		out.append(l.pop(nex[1]))
		g = nex[0]
	print(' '.join(map(str, out)))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	m = arr[0]
	res = [arr[0]]
	del arr[0]
	currgcd = m
	while arr:
		m = -1
		ind = -1
		el = -1
		for i in range(len(arr)):
			gc = gcd(currgcd, arr[i])
			if gc > m:
				m = gc
				ind = i
				el = arr[i]
		currgcd = gcd(el, currgcd)
		res.append(el)
		del arr[ind]
	print(*res)


import math

def ans(A):
	old_A = A[:]
	A = [(e, i) for (i, e) in enumerate(A)]
	running_gcd = 0
	ret = []
	while len(A):
		A = sorted(A)[::-1]
		running_gcd = math.gcd(running_gcd, A[0][0])
		ret += [A[0][1]]
		A = [(math.gcd(running_gcd, e), i) for (e, i) in A]
		A = A[1:]
	ret = [old_A[i] for i in ret]
	print(*ret)
T = int(input())
for t in range(T):
	input()
	A = list(map(int, input().split()))
	ans(A)


def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
T = int(input())
for t in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	A.sort()
	A.reverse()
	B = []
	C = [0] * N
	g = A[0]
	for i in range(N):
		mx = 1
		ind = i
		for j in range(0, N):
			if C[j] != -1:
				gc = gcd(g, A[j])
				if mx <= gc:
					mx = gc
					ind = j
		g = gcd(g, mx)
		C[ind] = -1
		B.append(A[ind])
	for b in B:
		print(b, end=' ')
	print('')


import sys
import math
from decimal import *

def I():
	return int(sys.stdin.readline())

def IL():
	return list(map(int, sys.stdin.readline().strip().split()))

def ILS():
	return list(map(str, sys.stdin.readline().strip().split()))

def solve():
	tt = I()
	for ii in range(tt):
		n = I()
		l = IL()
		l.sort(reverse=True)
		ans = [l[0]]
		cg = l[0]
		l[0] = -1
		while len(ans) < n:
			x = None
			tg = None
			for i in range(1, len(l)):
				if l[i] != -1:
					if x == None:
						x = i
						tg = math.gcd(l[i], cg)
					else:
						ttg = math.gcd(cg, l[i])
						if ttg > tg:
							x = i
							tg = ttg
			ans.append(l[x])
			cg = tg
			l[x] = -1
		for aa in ans:
			print(aa, end=' ')
		print()
solve()


def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def solve(n, arr):
	output = []
	output.append(max(arr))
	arr.remove(output[0])
	gcd__ = output[0]
	while len(arr) > 0:
		maxx = 0
		current_ind = 0
		i = 0
		while i < len(arr):
			gcd_ = gcd(gcd__, arr[i])
			if gcd_ > maxx:
				maxx = gcd_
				current_ind = i
			elif gcd_ == maxx:
				if arr[i] < arr[current_ind]:
					current_ind = i
			i += 1
		gcd__ = maxx
		output.append(arr[current_ind])
		arr.remove(arr[current_ind])
	output = map(str, output)
	return ' '.join(output)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	print(solve(n, arr))


import math
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	a = max(arr)
	ans = [a]
	arr.remove(a)
	l = n - 1
	GCD = [a]
	for k in range(n - 1):
		maxi = -1
		for j in range(l):
			temp = math.gcd(GCD[-1], arr[j])
			if temp > maxi:
				maxi = temp
				temp1 = arr[j]
		GCD.append(math.gcd(temp1, GCD[-1]))
		ans.append(temp1)
		arr.remove(temp1)
		l -= 1
	print(' '.join((str(x) for x in ans)))


import math
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	visit = [0 for _ in range(n)]
	curgcd = max(l)
	res = [curgcd]
	visit[l.index(curgcd)] = 1
	for i in range(n - 1):
		(temp, idx) = (-1, -1)
		for j in range(n):
			if visit[j] == 0 and math.gcd(curgcd, l[j]) > temp:
				temp = math.gcd(curgcd, l[j])
				idx = j
		res.append(l[idx])
		curgcd = temp
		visit[idx] = 1
	print(*res)


from sys import stdin
import math
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	a = [int(x) for x in inp().split()]
	a.sort()
	sett = set({n - 1})
	ans = [a[n - 1]]
	lastGcd = a[n - 1]
	for i in range(n - 1):
		maxi = -1
		cur = -1
		maxInd = -1
		for j in range(n - 1):
			if j not in sett:
				cur = math.gcd(lastGcd, a[j])
				if maxi < cur:
					maxi = cur
					maxInd = j
		lastGcd = maxi
		sett.add(maxInd)
		ans.append(a[maxInd])
	print(*ans)


import math
for i in range(int(input())):
	n = int(input())
	arr = [int(item) for item in input().split()]
	maxi = 0
	d = [False] * n
	j = -1
	for i in range(n):
		if arr[i] > maxi:
			maxi = arr[i]
			j = i
	brr = []
	brr.append(maxi)
	d[j] = True
	g = maxi
	e = -1
	while len(brr) < n:
		j = -1
		for i in range(n):
			if d[i] == False:
				r = math.gcd(g, arr[i])
				if r > e:
					e = r
					j = i
		brr.append(arr[j])
		d[j] = True
		g = e
		e = -1
	print(*brr)


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def factorial(n):
	if n == 0:
		return 1
	return n * factorial(n - 1)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return list(factors)

def sumDigits(no):
	return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10))
MOD = 1000000007
PMOD = 998244353
N = 10 ** 5
T = 1
T = int(stdin.readline())
for _ in range(T):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().rstrip().split()))
	a.sort(reverse=True)
	ans = []
	ans.append(a[0])
	d = {}
	g = a[0]
	for i in range(1, n):
		ix = -1
		g_val = 1
		for j in range(1, n):
			if j not in d:
				temp = gcd(g, a[j])
				if g_val <= temp:
					ix = j
					g_val = temp
		d[ix] = 0
		g = g_val
		ans.append(a[ix])
	print(*ans)


import sys
input = sys.stdin.readline
from collections import *
from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	flag = [False] * n
	ans = [0]
	now = 0
	for i in range(n):
		M = -1
		mark = -1
		for j in range(n):
			if flag[j]:
				continue
			g = gcd(now, a[j])
			if g > M:
				M = g
				mark = j
		ans.append(a[mark])
		flag[mark] = True
		now = gcd(now, a[mark])
	print(*ans[1:])


import math
T = int(input())
for _ in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	x = max(arr)
	g1 = x
	my_list = [max(arr)]
	arr.remove(max(arr))
	g = 1
	c = 1
	while True:
		p = arr.copy()
		for i in arr:
			if math.gcd(i, g1) > g:
				g = math.gcd(i, g1)
		if g == 1:
			for i in arr:
				my_list.append(i)
				c += 1
		else:
			for i in arr:
				if i % g == 0:
					p.remove(i)
					my_list.append(i)
					c += 1
		if c == n:
			break
		else:
			g1 = g
			g = 1
			arr = p
	print(*my_list)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def GCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for j in range(int(input())):
	n = int(input())
	vals = list(map(int, input().split()))
	cur = max(vals)
	ans = [cur]
	vals.remove(cur)
	for s in range(n - 1):
		maxsofar = 0
		num = 0
		for b in range(len(vals)):
			gcd = GCD(vals[b], cur)
			if gcd > maxsofar:
				maxsofar = gcd
				num = vals[b]
		cur = maxsofar
		ans.append(num)
		vals.remove(num)
	print(*ans)


from math import gcd
for T in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())), reverse=True)
	g = a[0]
	for i in range(n):
		Max = 0
		ind = i
		for j in range(i, n):
			if gcd(g, a[j]) > Max:
				Max = gcd(g, a[j])
				ind = j
		g = Max
		(a[i], a[ind]) = (a[ind], a[i])
	print(*a)


import sys
from collections import defaultdict
from math import gcd
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	res = []
	lis.sort(reverse=True)
	res.append(lis[0])
	g = lis[0]
	lis[0] = -1
	for i in range(n - 1):
		m = -1
		mi = -1
		for j in range(n):
			if lis[j] != -1:
				x = gcd(g, lis[j])
				if m < x:
					m = x
					mi = j
		res.append(lis[mi])
		g = m
		lis[mi] = -1
	print(*res)


import math

def solve(n, a):
	b = [max(a)]
	c = [max(a)]
	a.remove(max(a))
	while len(a) > 0:
		best = 0
		for i in range(1, len(a)):
			if math.gcd(c[-1], a[i]) > math.gcd(c[-1], a[best]):
				best = i
		b.append(a[best])
		c.append(math.gcd(c[-1], a[best]))
		a.pop(best)
	return ' '.join((str(b[i]) for i in range(n)))
t = int(input())
for t in range(t):
	n = int(input())
	a = [int(s) for s in input().split()]
	result = solve(n, a)
	print(result)


from sys import stdin
input = stdin.buffer.readline

def computeGCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def func():
	final = [a[0]]
	a[0] = -1
	main_gcd = final[0]
	for i in range(n):
		ind = -1
		num = 1
		for j in range(1, n):
			if a[j] != -1:
				temp = computeGCD(main_gcd, a[j])
				if num < temp:
					ind = j
					num = temp
		if ind != -1:
			final.append(a[ind])
			a[ind] = -1
			main_gcd = num
		else:
			break
	for k in a:
		if k != -1:
			final.append(k)
	print(*final)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	func()


tc = int(input())
import math

def get_factors(n):
	facs = set()
	for i in range(1, int(math.sqrt(n)) + 1):
		if n % i == 0:
			facs.add(i)
			facs.add(n // i)
	return facs
for _ in range(tc):
	n = int(input())
	a = [int(x) for x in input().strip().split()]
	big = max(a)
	b = [big]
	ongoing = get_factors(big)
	a.remove(big)
	facs = []
	for e in a:
		facs.append(get_factors(e))
	while len(a) > 0:
		biggest = 0
		biggesti = -1
		for i in range(len(a)):
			current = max(ongoing & facs[i])
			if current > biggest:
				biggest = current
				biggesti = i
		b.append(a[biggesti])
		ongoing = facs[biggesti] & ongoing
		del a[biggesti]
		del facs[biggesti]
	print(' '.join([str(x) for x in b]))


from math import sqrt
from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	b = sorted(a, reverse=True)
	for i in a:
		d[i] = d.get(i, 0) + 1
	ni = b[0]
	ans = []
	start = b[0]
	for i in range(n):
		mx = 1
		ag = -1
		for j in b:
			if d[j] > 0:
				g = gcd(ni, j)
				if g > mx:
					mx = g
					ag = j
		if ag == -1:
			if d[start] > 0:
				ans.append(start)
				d[start] -= 1
			start = -1
			for p in b:
				if d[p] > 0:
					start = p
					break
		else:
			ni = mx
			if d[ag] > 0:
				ans.append(ag)
				d[ag] -= 1
	for i in d:
		if d[i] > 0:
			ans += [i] * d[i]
	print(*ans)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	visited = [0] * n
	visited[n - 1] = 1
	num = arr[-1]
	sequence = [arr[-1]]
	for i in range(n - 1):
		index = -1
		gcd1 = -1
		for j in range(n):
			if visited[j] == 0:
				if gcd(num, arr[j]) > gcd1:
					gcd1 = gcd(num, arr[j])
					index = j
		num = gcd1
		visited[index] = 1
		sequence.append(arr[index])
	print(*sequence)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	lst = list(map(int, input().strip().split()))
	lst = sorted(lst, reverse=True)
	n = len(lst)
	ans = lst[0]
	for i in range(1, n):
		for j in range(i + 1, n):
			if math.gcd(ans, lst[i]) < math.gcd(ans, lst[j]):
				(lst[j], lst[i]) = (lst[i], lst[j])
		ans = math.gcd(ans, lst[i])
	print(*lst)


MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
from collections import *
for _ in range(ii()):
	cdn = 0

	def find_gcd(x, y):
		while y:
			(x, y) = (y, x % y)
		return x
	n = ii()
	a = il()
	cdn = cdn + 1
	a.sort(reverse=True)
	gcd = a[0]
	ans = [a[0]]
	for i in range(0, n):
		mx = 0
		lpn = 0
		lpn = lpn + 1
		for i in range(1, len(a)):
			zpn = 0
			mx = max(mx, find_gcd(gcd, a[i]))
		for i in range(1, len(a)):
			spm = 0
			ld = find_gcd(gcd, a[i])
			if ld == mx:
				rpn = 0
				ans.append(a[i])
				a[i] = -1
				kdn = 0
				gcd = mx
				break
	for i in range(0, n):
		print(ans[i], end=' ')
	print('')
	kls = 0


t = int(input())
for ii in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	ans = [a[0]]
	used = [False] * n
	used[0] = True

	def gcd(a, b):
		if a % b == 0:
			return b
		return gcd(b, a % b)
	maxgcdsofar = ans[-1]
	for i in range(n - 1):
		done = 0
		idx = None
		for j in range(1, n):
			if not used[j]:
				num = gcd(maxgcdsofar, a[j])
				if num > done:
					done = num
					idx = j
		ans.append(a[idx])
		maxgcdsofar = done
		used[idx] = True
	print(*ans)


import sys
input = sys.stdin.readline

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	m = max(arr)
	(tmp_m, tmp_gcd, idx) = (-1, -1, 0)
	n_arr = [m]
	arr.remove(m)
	while arr:
		(tmp_m, tmp_gcd, idx) = (0, 0, 0)
		for i in range(len(arr)):
			now_gcd = gcd(m, arr[i])
			now_num = arr[i]
			if now_gcd > tmp_gcd:
				tmp_num = now_num
				tmp_gcd = now_gcd
				idx = i
			elif now_gcd == tmp_gcd and now_num > tmp_num:
				tmp_num = now_num
				idx = i
		n_arr.append(arr[idx])
		arr.remove(arr[idx])
		m = tmp_gcd
	print(*n_arr)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	s = dict()
	for i in a:
		s[i] = 0
	for i in a:
		s[i] += 1
	a = list(set(a))
	max_a = max(a)
	ans = [max_a] * s[max_a]
	visited = [False] * len(a)
	visited[a.index(max_a)] = True
	temp = max_a
	for i in range(len(a)):
		max_ = 1
		x = ans[-1]
		for j in range(len(a)):
			if not visited[j] and max_ < math.gcd(temp, a[j]):
				max_ = math.gcd(temp, a[j])
				y = a[j]
				idx = j
		if max_ != 1:
			ans += [y] * s[y]
			visited[idx] = True
			temp = max_
		else:
			break
	for i in range(len(a)):
		if not visited[i]:
			ans += [a[i]] * s[a[i]]
	for i in ans:
		print(i, end=' ')
	print()


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	ans = []
	ans.append(arr[0])
	visited = [0] * n
	visited[0] = 1
	lastgc = arr[0]
	for i in range(1, n):
		maxi = -1
		index = -1
		original = ''.join((str(x) for x in ans))
		s1 = original
		for j in range(n):
			if visited[j] != 1:
				gc = gcd(lastgc, arr[j])
				if gc > maxi:
					maxi = gc
					index = j
					s1 = original + str(gc)
		visited[index] = 1
		ans.append(arr[index])
		lastgc = maxi
	print(' '.join((str(i) for i in ans)))


from sys import stdin, stdout, setrecursionlimit
import heapq
from math import gcd, ceil, sqrt
from collections import Counter, deque
from bisect import bisect_left, bisect_right
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
setrecursionlimit(100000)
mod = 1000000007
tc = ii1()
for _ in range(tc):
	n = ii1()
	arr = sorted(iia(), reverse=True)
	ans = [arr[0]]
	cur_gcd = arr[0]
	seen = set([0])
	while len(seen) < n:
		cur = None
		for i in range(len(arr)):
			if i not in seen:
				temp = gcd(cur_gcd, arr[i])
				if cur == None:
					cur = [temp, i]
				elif temp > cur[0]:
					cur = [temp, i]
				elif temp == cur[0] and arr[i] > cur[1]:
					cur = [temp, i]
		ans.append(arr[cur[1]])
		cur_gcd = gcd(cur_gcd, arr[cur[1]])
		seen.add(cur[1])
	print(*ans)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for t in range(int(input())):
	n = int(input())
	nums = list(map(int, input().split()))
	used = [False] * n
	res = []
	mai = 0
	for i in range(n):
		if nums[i] > nums[mai]:
			mai = i
	used[mai] = True
	res.append(nums[mai])
	cai = 1
	lg = res[0]
	while True:
		cai = -1
		mg = 0
		for i in range(n):
			if not used[i]:
				gg = gcd(lg, nums[i])
				if cai < 0 or gg > mg or (gg == mg and nums[i] > nums[cai]):
					cai = i
					mg = gg
		if cai < 0:
			break
		lg = mg
		used[cai] = True
		res.append(nums[cai])
	print(*res)


from collections import defaultdict
from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	num = max(a)
	indices = set([a.index(num)])
	print(num, end=' ')
	for __ in range(1, len(a)):
		cur_gcd = -1
		cur_num = 1001
		cur_ind = -1
		for (j, elem) in enumerate(a):
			if j not in indices:
				g = gcd(num, a[j])
				if g > cur_gcd or (g == cur_gcd and a[j] < cur_num):
					cur_gcd = g
					cur_num = a[j]
					cur_ind = j
		indices.add(cur_ind)
		print(cur_num, end=' ')
		num = gcd(num, cur_num)
	print()


import math
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	out = []
	for i in range(arr.count(arr[-1])):
		out.append(arr.pop())
	p = out[-1]
	while len(arr) != 0:
		g = 1
		todel = []
		for i in range(len(arr)):
			if math.gcd(p, arr[i]) > g:
				g = math.gcd(p, arr[i])
				todel = [i]
			elif math.gcd(p, arr[i]) == g:
				todel.append(i)
		todel.reverse()
		p = g
		for i in todel:
			out.append(arr.pop(i))
	print(*out)


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
N = 10 ** 10 + 7
for _ in range(I()):
	n = I()
	a = sorted(R(), reverse=True)
	b = [a[0]]
	a.remove(a[0])
	g = b[0]
	for i in range(1, n):
		mx = 0
		id = 0
		for j in range(n - i):
			v = gcd(g, a[j])
			if v > mx:
				mx = v
				id = a[j]
		g = mx
		b += (id,)
		a.remove(id)
	print(*b)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	vis = [False for i in range(n)]
	ans = [arr[0]]
	vis[0] = True
	cnt = 1
	g = arr[0]
	while cnt != n:
		temp = []
		for i in range(n):
			if vis[i] == False:
				temp.append([-gcd(arr[i], g), -arr[i]])
		temp.sort()
		cur = -temp[0][1]
		g = gcd(g, cur)
		ans.append(cur)
		cnt += 1
		for i in range(n):
			if arr[i] == cur and vis[i] == False:
				vis[i] = True
				break
	print(*ans)


from math import gcd
import sys
input = sys.stdin.buffer.readline

def main():
	Q = int(input())
	for _ in range(Q):
		N = int(input())
		A = list(map(int, input().split()))
		gmax = 0
		p = -1
		for (i, a) in enumerate(A):
			if a > gmax:
				gmax = a
				p = i
		ans = [str(A[p])]
		remain = set(range(N))
		remain.remove(p)
		nowg = A[p]
		while len(remain) > 0:
			gmax = 0
			np = -1
			for r in remain:
				g = gcd(A[r], nowg)
				if g > gmax:
					gmax = g
					np = r
			remain.remove(np)
			ans.append(str(A[np]))
			nowg = gcd(A[np], nowg)
		print(' '.join(ans))
main()


import math
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	ar.sort(reverse=True)
	ans = [0]
	key = {0}
	nu = 1
	pre = ar[0]
	while nu != n:
		ma = 0
		ne = 0
		for j in range(n):
			if not j in key:
				gc = math.gcd(pre, ar[j])
				if gc > ma:
					ma = gc
					ne = j
		pre = ma
		ans.append(ne)
		nu += 1
		key.add(ne)
	final = []
	for i in ans:
		final.append(ar[i])
	print(*final)


import math, sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, a, b, gcd_prefix) = (int(input()), [int(i) for i in input().split()], [], 0)
	while a:
		cache = max(a, key=lambda x: math.gcd(x, gcd_prefix))
		gcd_prefix = math.gcd(cache, gcd_prefix)
		b.append(cache)
		a.remove(cache)
	print(*b)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = int(input())
for x in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	gc = a[0]
	print(a[0], end=' ')
	a.remove(a[0])
	while len(a):
		max = 0
		for i in a:
			temp = gcd(gc, i)
			if temp > max:
				max = temp
				ele = i
		gc = max
		print(ele, end=' ')
		a.remove(ele)
	print('\n')


from sys import stdin

class Input:

	def readline(self):
		return stdin.readline().strip()

	def read_list(self):
		return self.readline().split()

	def read_ints(self):
		return list(map(int, self.read_list()))

	def known_tests(self):
		(cases,) = self.read_ints()
		for case in range(cases):
			yield self

	def single_test(self):
		yield self

class Problem:

	def __init__(self, input):
		(n,) = input.read_ints()
		a = input.read_ints()
		g = [0 for i in range(n)]
		a.sort(reverse=True)
		g[0] = a[0]
		le = 1
		while le < n:
			for ri in range(le, n):
				g[ri] = self.gcd(g[le - 1], a[ri])
			mx = max(g[le:])
			l = le
			ri = le
			while ri < n:
				if mx == g[ri]:
					(a[le], a[ri]) = (a[ri], a[le])
					(g[le], g[ri]) = (g[ri], g[le])
					le += 1
				ri += 1
			a[l:le] = sorted(a[l:le])
		print(*tuple(a))

	def gcd(self, a, b):
		return a if b == 0 else self.gcd(b, a % b)
for test_input in Input().known_tests():
	Problem(test_input)


ii = lambda : int(input())
il = lambda : list(map(int, input().split()))
for _ in range(ii()):

	def find_gcd(x, y):
		while y:
			(x, y) = (y, x % y)
		return x
	n = ii()
	a = il()
	a.sort(reverse=True)
	gcd = a[0]
	ans = [a[0]]
	for i in range(0, n):
		mx = 0
		for i in range(1, len(a)):
			mx = max(mx, find_gcd(gcd, a[i]))
		for i in range(1, len(a)):
			ld = find_gcd(gcd, a[i])
			if ld == mx:
				ans.append(a[i])
				a[i] = -1
				gcd = mx
				break
	for i in range(0, n):
		print(ans[i], end=' ')
	print('')


from sys import stdin
from math import gcd
T = int(stdin.readline().strip())
for caso in range(T):
	n = int(stdin.readline().strip())
	s = list(map(int, stdin.readline().strip().split()))
	s.sort()
	s = s[::-1]
	ans = [s[0]]
	s.remove(s[0])
	last = ans[0]
	for i in range(n - 1):
		mx = -1
		a = -1
		for j in s:
			z = gcd(j, last)
			if z > mx:
				mx = z
				a = j
		ans.append(a)
		s.remove(a)
		last = gcd(last, a)
	print(*ans)


from math import gcd as bltin_gcd

def coprime2(a, b):
	return bltin_gcd(a, b)
t = int(input())
from collections import defaultdict
for i in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))[:n]
	visited = defaultdict(int)
	ans = [0] * n
	cd = 0
	for i in range(n):
		temp = 0
		val = 0
		for j in range(n):
			if visited[j] == False and coprime2(cd, arr[j]) > temp:
				temp = coprime2(cd, arr[j])
				val = j
		visited[val] = True
		cd = temp
		ans[i] = arr[val]
	for num in ans:
		print(num, end=' ')
	print()


import math
from collections import defaultdict
from collections import Counter
import itertools

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def solve(A):
	n = len(A)
	res = []
	ma = float('-inf')
	k = 0
	A.sort()
	g = A[n - 1]
	res.append(A[n - 1])
	A[n - 1] = -1
	for i in range(1, n):
		ma = float('-inf')
		k = 0
		for j in range(0, n):
			if A[j] != -1:
				if gcd(A[j], g) >= ma:
					k = j
					ma = gcd(A[j], g)
		res.append(A[k])
		g = gcd(g, A[k])
		A[k] = -1
	return res
t = int(input())
while t:
	temp = []
	n = int(input())
	in_ = map(int, input().split(' '))
	for x in in_:
		temp.append(int(x))
	print(*solve(temp))
	t -= 1


from __future__ import division, print_function
import os
import sys
from math import gcd
from collections import Counter
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = [int(ai) for ai in input().split()]
		m = max(a)
		used = [False] * n
		sol = [0] * n
		cur = m
		for i in range(n):
			idx = -1
			best = 0
			for j in range(n):
				if not used[j]:
					g = gcd(cur, a[j])
					if best < g:
						best = g
						idx = j
			used[idx] = True
			sol[i] = a[idx]
			cur = gcd(sol[i], cur)
		print(*sol)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	a = inlt()
	q = [max(a)]
	w = [0] * len(a)
	w[a.index(max(a))] = 1
	qw = max(a)
	while len(q) < len(a):
		qq = -1
		for j in range(len(a)):
			if w[j] == 0:
				if math.gcd(qw, a[j]) > qq:
					qq = math.gcd(qw, a[j])
					ww = j
		q.append(a[ww])
		w[ww] = 1
		qw = math.gcd(qw, q[-1])
	print(*q)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


from math import gcd
from collections import Counter

def find_ans(n, s):
	u = max(s)
	ans = [u]
	p = dict(Counter(s))
	qq = {}
	qq[u] = 1
	q = u
	j = 0
	Max = -10
	for oo in range(n - 1):
		for i in range(n):
			if gcd(q, s[i]) > Max and qq.get(s[i], 0) < p[s[i]]:
				Max = gcd(q, s[i])
				j = i
		ans.append(s[j])
		qq[s[j]] = qq.get(s[j], 0) + 1
		q = Max
		Max = -10
	print(*ans)
for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	find_ans(n, s)


import io
import os
from collections import Counter, defaultdict, deque
from math import gcd

def solve(N, A):
	A.sort()
	ans = [A.pop()]
	g = ans[-1]
	while A:
		best = (0,)
		for (i, x) in enumerate(A):
			best = max(best, (gcd(g, x), i))
		ans.append(A.pop(best[1]))
		g = gcd(g, ans[-1])
	return ' '.join(map(str, ans))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N,) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	ans = solve(N, A)
	print(ans)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
inp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
ceil = lambda x: int(x) if x == int(x) else int(x) + 1
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
stdarr = lambda : map(int, stdstr().split())
mod = 1000000007
for _ in range(stdint()):
	n = stdint()
	arr = list(stdarr())
	arr = sorted(arr, reverse=True)
	m = max(arr)
	res = [arr[0]]
	del arr[0]
	currgcd = m
	while arr:
		m = -1
		ind = -1
		el = -1
		for i in range(len(arr)):
			gc = gcd(currgcd, arr[i])
			if gc > m:
				m = gc
				ind = i
				el = arr[i]
		currgcd = gcd(el, currgcd)
		res.append(el)
		del arr[ind]
	print(*res)


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def func2(arr, n):
	arr2 = []
	for i in range(0, n):
		arr2.append(0)
	arr3 = []
	maxe = 0
	maxi = 0
	i = 0
	for e in arr:
		if maxe < e:
			maxe = e
			maxi = i
		i += 1
	arr3.append(maxe)
	arr2[maxi] = 1
	ogcd = arr3[-1]
	first = arr3[-1]
	while len(arr3) != n:
		count = 0
		for i in range(0, n):
			if arr2[i] != 1:
				if count == 0:
					fgcd = gcd(ogcd, arr[i])
					j = i
					count += 1
				gcd1 = gcd(ogcd, arr[i])
				if gcd1 > fgcd:
					fgcd = gcd1
					j = i
		if fgcd == 1:
			for i in range(0, n):
				if arr2[i] != 1:
					arr3.append(arr[i])
		else:
			arr3.append(arr[j])
			arr2[j] = 1
			ogcd = fgcd
	for e in arr3:
		print(e, end=' ')
	print()
	return
for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	func2(arr, n)


import sys
from math import gcd
pprint = lambda s: print(' '.join(map(lambda x: str(x), s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input
for i in range(int(ipnut())):
	n = int(ipnut())
	a = list(map(int, input().split()))
	g = 0
	ans = []
	for i in range(n):
		mi = 0
		mo = 0
		for j in range(len(a)):
			if mo < gcd(g, a[j]):
				mo = gcd(g, a[j])
				mi = j
		g = mo
		ans.append(a[mi])
		del a[mi]
	pprint(ans)


from collections import defaultdict
from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	res = [a[0]]
	val = a[0]
	k = 1
	lol = [[0, a[i]] for i in range(n)]
	while k < n:
		ans = []
		for i in range(k, n):
			ans.append([gcd(val, lol[i - k + 1][1]), lol[i - k + 1][1]])
		lol = sorted(ans, key=lambda x: -x[0])
		res.append(lol[0][1])
		val = gcd(val, lol[0][1])
		k += 1
	print(*res)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	ans = list()
	ans.append(arr[0])
	c = arr[0]
	arr[0] = 0
	for i in range(1, n):
		(idx, maxx) = (None, -1)
		for j in range(n):
			if arr[j] == 0:
				continue
			g = gcd(c, arr[j])
			if g > maxx:
				maxx = g
				idx = j
		ans.append(arr[idx])
		c = maxx
		arr[idx] = 0
	print(*ans)


import math
import collections

def solution(n, a):
	max_ = max(a)
	max_i = a.index(max_)
	x = [max_]
	del a[max_i]
	gcd = max_
	while a != []:
		out = collections.defaultdict(list)
		for e in a:
			out[math.gcd(gcd, e)].append(e)
		temp = out.pop(max(list(out.keys())))
		x.extend(temp)
		for e in temp:
			a.remove(e)
		gcd = math.gcd(gcd, temp[0])
	return x
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	print(*solution(n, a))


import sys
import math
input = sys.stdin.readline
cases = int(input())
for case in range(cases):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort(reverse=True)
	c = [a[0]]
	ans = [a[0]]
	cnt = 1
	vis = [False] * len(a)
	vis[0] = True
	while cnt < n:
		gcd = 1
		for i in range(len(a)):
			if not vis[i]:
				gcd = max(math.gcd(a[i], c[-1]), gcd)
		for i in range(len(a)):
			if math.gcd(a[i], c[-1]) == gcd and (not vis[i]):
				vis[i] = True
				ans.append(a[i])
				cnt += 1
		c.append(gcd)
	print(*ans)


import math
cases = int(input())
for t in range(cases):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)[::-1]
	v1 = a[0]
	for i in range(n - 2):
		mv = 0
		pos = -1
		v1 = math.gcd(v1, a[i])
		for j in range(i + 1, n):
			v = math.gcd(v1, a[j])
			if v > mv:
				mv = v
				pos = j
		if pos > i:
			(a[i + 1], a[pos]) = (a[pos], a[i + 1])
	print(*a)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	base = 0
	for i in range(n):
		base = max(base, a[i])
	maxi = base
	visit = [0 for i in range(maxi + 1)]
	for i in range(n):
		visit[a[i]] += 1
	c = []
	i = base
	while i > 0:
		j = maxi
		while j > 0:
			if visit[j] > 0 and j % i == 0 and (base % i == 0):
				for k in range(visit[j]):
					c.append(j)
				visit[j] = 0
				base = i
			j -= 1
		i -= 1
	for i in c:
		print(i, end=' ')
	print()


t = int(input())
for _ in range(t):
	from math import gcd
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	b.append(max(a))
	a.pop(a.index(max(a)))
	c = b[0]
	for i in range(n - 1):
		m = 1
		k = 0
		for j in range(n - 1 - i):
			if gcd(a[j], c) > m:
				k = j
				m = gcd(a[j], c)
		c = m
		b.append(a[k])
		a.pop(k)
	print(*b)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
from collections import Counter, defaultdict, deque

def int1():
	return int(input())

def map1():
	return map(int, input().split())

def list1():
	return list(map(int, input().split()))

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
mod = pow(10, 9) + 7

def solve():
	n = int1()
	l1 = list1()
	l1.sort()
	v = l1.pop()
	l2 = []
	l2.append(v)
	n = len(l1)
	x = v
	c = 0
	while c < n:
		max1 = -1
		for j in range(n):
			if l1[j] != 'a':
				v = gcd(x, l1[j])
				if max1 < v:
					max1 = v
					a = l1[j]
					b = j
		l2.append(a)
		l1[b] = 'a'
		c = c + 1
		x = max1
	print(*l2)
for _ in range(int(input())):
	solve()


import math
t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	g = 0
	for i in range(n):
		mj = 0
		for j in range(n - i):
			if math.gcd(g, a[j]) > math.gcd(g, a[mj]):
				mj = j
		g = math.gcd(g, a[mj])
		print(a[mj], end=' ')
		a = a[:mj] + a[mj + 1:]
	print()
	t -= 1


import sys

def gcd(a, b):
	(a, b) = (max(a, b), min(a, b))
	if b == 0:
		return a
	else:
		return gcd(a % b, b)

def input():
	return sys.stdin.readline().rstrip()

def deleteValAndRecalculate(arr, i, gcd_0toi, gcd_iton):
	arr.pop(i)
	for j in range(i, len(arr)):
		gcd_iton[j] = gcd_iton[j + 1]
		gcd_0toi[j] = gcd(arr[j], gcd_0toi[j - 1])
	for j in range(i - 1, -1, -1):
		gcd_iton[j] = gcd(arr[j], gcd_iton[j + 1])
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = []
	first_val = max(arr)
	ans.append(first_val)
	present_gcd = first_val
	arr.remove(first_val)
	while len(arr) > 0:
		max_gcd = gcd(arr[0], present_gcd)
		max_val_pos = 0
		for j in range(1, len(arr)):
			temp_gcd = gcd(present_gcd, arr[j])
			if temp_gcd > max_gcd:
				max_val_pos = j
				max_gcd = temp_gcd
		ans.append(arr[max_val_pos])
		arr.pop(max_val_pos)
		present_gcd = max_gcd
	print(' '.join(map(str, ans)))


import math
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = sorted(list(map(int, input().split())), reverse=True)
	b = []
	b.append(a[0])
	a.remove(a[0])
	for j in range(1, n):
		i = 0
		tem = 1
		if j == 1:
			mx = b[0]
		while i < len(a):
			k = math.gcd(mx, a[i])
			if k >= tem:
				tem = k
				relee = a[i]
			i += 1
		mx = math.gcd(mx, relee)
		a.remove(relee)
		b.append(relee)
	print(*b)


def gcd(x, y):
	while x % y > 0:
		(x, y) = (y, x % y)
	return y
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	f = [0] * n
	f[0] = 1
	ans = [a[0]]
	pgcd = a[0]
	for i in range(1, n):
		gmax = -1
		imax = -1
		for j in range(n):
			if f[j] == 0:
				t = gcd(pgcd, a[j])
				if t > gmax:
					gmax = t
					imax = j
		f[imax] = 1
		pgcd = gcd(pgcd, a[imax])
		ans.append(a[imax])
	print(*ans)


import math
t = int(input())
for i in range(t):
	l = input()
	a = list(map(int, input().split()))
	n = max(a)
	print(n, end=' ')
	del a[a.index(n)]
	while len(a) > 0:
		m = 1
		mi = 0
		for i in range(len(a)):
			g = math.gcd(a[i], n)
			if g > m:
				m = g
				mi = i
		n = m
		print(a[mi], end=' ')
		del a[mi]
	print()


import sys

def gcd(a, b):
	while b != 0:
		(a, b) = (b, a % b)
	return a
t = int(sys.stdin.readline())
for i in range(t):
	n = int(sys.stdin.readline())
	a = [int(j) for j in sys.stdin.readline().split()]
	arr = []
	for p in range(n):
		arr.append(False)
	ans = []
	ans.append(max(a))
	val = max(a)
	for h in range(n):
		if val == a[h]:
			arr[h] = True
			break
	cur = ans[0]
	for k in range(1, n):
		cur = gcd(cur, ans[-1])
		mx = 0
		ctr = 0
		ind = -2
		for f in range(n):
			tmp = gcd(cur, a[f])
			if tmp > mx and arr[f] == False:
				mx = tmp
				ind = f
		ans.append(a[ind])
		arr[ind] = True
	for p in range(n):
		print(ans[p], end=' ')
	print()


def Sort(sub_li, y):
	sub_li.sort(key=lambda x: x[y])
	return sub_li

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
a = int(input())
for j in range(a):
	b = int(input())
	c = [int(x) for x in input().split()]
	z = []
	y = []
	for j in range(b):
		z.append(c[j])
	x1 = max(c)
	y.append(x1)
	for j in range(b):
		d = []
		d.append(c[j])
		d.append(gcd(x1, c[j]))
		c[j] = d
	count = -100
	Sort(c, 1)
	c.pop()
	for j in range(len(c)):
		for k in range(len(c)):
			c[k][1] = gcd(x1, c[k][1])
		Sort(c, 1)
		x1 = gcd(x1, c[len(c) - 1][1])
		y.append(c[len(c) - 1][0])
		c.pop()
	for j in range(b):
		print(y[j], end=' ')
	print()


def nod(a, b):
	if a == 1 or b == 1:
		return 1
	while a != b:
		if a > b:
			a = a - b
		else:
			b = b - a
	return a
n = int(input())
i = 0
while i < n:
	q = int(input())
	mas = [int(j) for j in input().split()]
	new_mas = []
	new_mas.append(max(mas))
	mas.remove(max(mas))
	j = 0
	max_nod = new_mas[0]
	while len(mas) > 0:
		nd = 1
		num = 0
		for j in range(len(mas)):
			nd1 = nod(max_nod, mas[j])
			if nd1 > nd:
				nd = nd1
				num = j
		if nd != 1:
			new_mas.append(mas[num])
			mas.pop(num)
			max_nod = nd
		else:
			for j in mas:
				new_mas.append(j)
			mas.clear()
	for j in new_mas:
		print(j, end=' ')
	print()
	i += 1


import sys
from math import gcd

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	N = INT()
	A = LIST()
	b = c = max(A)
	ans = [b]
	A.pop(A.index(b))
	for _ in range(N - 1):
		g = 0
		for a in A:
			if gcd(c, a) > g:
				g = gcd(c, a)
				b = a
		c = g
		ans.append(b)
		A.pop(A.index(b))
	print(*ans)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
gans = []
for _ in range(int(input())):
	n = int(input())
	u = list(map(int, input().split()))
	ans = []
	cur = max(u)
	a = [0] * n
	a[u.index(cur)] = 1
	ans.append(cur)
	for i in range(1, n):
		ansi = -1
		ind = -1
		for j in range(n):
			if a[j]:
				continue
			g = gcd(cur, u[j])
			if g > ansi:
				ansi = g
				ind = j
		a[ind] = 1
		ans.append(u[ind])
		cur = ansi
	gans.append(' '.join(map(str, ans)))
print('\n'.join(gans))


import math
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	while False:
		break
	maxel = max(a)
	ans = list()
	for j in range(n):
		if maxel == 1:
			break
		maxgcd = math.gcd(maxel, a[0])
		ind = 0
		for k in range(n):
			if math.gcd(maxel, a[k]) > maxgcd:
				maxgcd = math.gcd(maxel, a[k])
				ind = k
		ans.append(a[ind])
		a[ind] = -1
		maxel = maxgcd
	for j in a:
		if j != -1:
			ans.append(j)
	for j in ans:
		if j == -1:
			continue
		print(j, end=' ')
	print('')


from math import gcd
for _ in range(int(input())):
	N = int(input())
	A = list(map(int, input().split()))
	b = max(A)
	c = max(A)
	ans = [b]
	A.pop(A.index(b))
	for _ in range(N - 1):
		g = 0
		for a in A:
			if gcd(c, a) > g:
				g = gcd(c, a)
				b = a
		c = g
		ans.append(b)
		A.pop(A.index(b))
	print(*ans)


def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def run_test():
	n = int(input())
	a = list(map(int, input().split()))
	a = [(x, x) for x in a]
	res = []
	while a:
		(next_gcd, next_val) = max(a)
		a.remove((next_gcd, next_val))
		res.append(next_val)
		a = [(gcd(next_gcd, v), x) for (v, x) in a]
	print(*res)

def main():
	t = int(input())
	for _ in range(t):
		run_test()
main()


import math
t = int(input())
for _ in range(t):
	n = int(input())
	ls = list(map(int, input().split()))
	mi = max(ls)
	ind = ls.index(mi)
	ls[ind] = 0
	b = [mi]
	cg = b[0]
	for i in range(1, n):
		ci = 0
		cans = 0
		for j in range(n):
			if ls[j] != 0 and cans < math.gcd(cg, ls[j]):
				cans = math.gcd(cg, ls[j])
				ci = j
		b.append(ls[ci])
		cg = cans
		ls[ci] = 0
	print(*b)


from sys import setrecursionlimit
import threading

def gcdofab(a, b):
	if a == 0:
		return b
	return gcdofab(b % a, a)

def main():
	test = int(input())
	for _ in range(test):
		n = int(input())
		arr = list(map(int, input().split()))
		arr.sort()
		visited = [0] * n
		visited[-1] = 1
		ans = [arr.pop()]
		a = ans[0]
		for i in range(1, n):
			cur = [0, 0]
			for j in range(n):
				if visited[j] == 0:
					nc = gcdofab(arr[j], a)
					if nc > cur[0]:
						cur = [nc, j]
			a = cur[0]
			j = cur[-1]
			visited[j] = 1
			ans.append(arr[j])
		for gg in ans:
			print(gg, end=' ')
		print()
setrecursionlimit(10000)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


from functools import lru_cache

@lru_cache(maxsize=None)
def gcd(a, b):
	if a % b == 0:
		return b
	return gcd(b, a % b)
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = []
	b.append(max(a))
	a.remove(max(a))
	curr = b[0]
	for _ in range(n - 1):
		bestGcd = -1
		bestIndex = -1
		for (i, ai) in enumerate(a):
			if gcd(curr, ai) > bestGcd:
				bestGcd = gcd(curr, ai)
				bestIndex = i
		curr = bestGcd
		b.append(a[bestIndex])
		del a[bestIndex]
	print(*b)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	acc = 0
	res = []
	while len(arr) > 0:
		mx = arr[0]
		for e in arr[1:]:
			if gcd(e, acc) > gcd(mx, acc):
				mx = e
		acc = gcd(acc, mx)
		arr.remove(mx)
		res.append(mx)
	print(*res)


import sys
import itertools

def gcd(a, b):
	if a == b:
		return a
	elif a < b:
		return gcd(a, b - a)
	else:
		return gcd(a - b, b)
n = int(sys.stdin.readline())
for i in range(n):
	s = int(sys.stdin.readline())
	data = [(int(i), int(i)) for i in sys.stdin.readline().split()]
	stack = []
	it = 0
	while data:
		data = sorted(data, reverse=True)
		if data[0][1] == 1:
			break
		print(data[0][1], end=' ')
		answers = []
		for (gcd_value, value) in itertools.islice(data, 1, len(data)):
			answers.append((gcd(gcd_value, data[0][0]), value))
		data = answers
	for (gcd_value, value) in data:
		print(value, end=' ')
	print('')


import math
for y in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	j = 1
	index = -1
	g = l[0]
	while j < n:
		temp = 0
		for i in range(j, n):
			y = math.gcd(g, l[i])
			if y > temp:
				temp = y
				index = i
		(l[j], l[index]) = (l[index], l[j])
		g = temp
		j += 1
	print(*l)


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	from math import gcd
	input = sys.stdin.buffer.readline
	for _ in range(int(input())):
		N = int(input())
		A = list(map(int, input().split()))
		A.sort()
		cur = A[-1]
		ans = [cur]
		A.pop()
		for _ in range(N - 1):
			G = []
			for a in A:
				G.append((gcd(cur, a), a))
			G.sort(key=lambda x: x[0])
			(cur, a) = G.pop()
			ans.append(a)
			A = [Gj[1] for Gj in G]
		print(*ans)
main()


from functools import lru_cache
from sys import stdin, stdout
import sys
from math import *
input = stdin.readline
for __ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	m = max(ar)
	ans = [m]
	no = []
	yes = []
	for i in range(n):
		if gcd(m, ar[i]) == 1:
			no.append(ar[i])
		else:
			yes.append(ar[i])
	g = m
	yes.sort()
	yes.pop()
	yes = yes[::-1]
	temp = [0] * len(yes)
	for i in range(len(yes)):
		t = 1
		for j in range(len(yes)):
			if temp[j] == 0:
				ind = j
		for j in range(len(yes)):
			if gcd(g, yes[j]) > t and temp[j] == 0:
				ind = j
				t = gcd(g, yes[j])
		ans.append(yes[ind])
		g = t
		temp[ind] = 1
	print(*ans + no)


import sys
import math
input = sys.stdin.readline
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	ans = [max(a)]
	curr = ans[0]
	d[ans[0]] -= 1
	if d[ans[0]] == 0:
		del d[ans[0]]
	while d and curr != 1:
		m = 0
		e = -1
		for i in d:
			x = math.gcd(i, curr)
			if x > m:
				m = x
				e = i
		curr = m
		ans.append(e)
		d[e] -= 1
		if d[e] == 0:
			del d[e]
	for i in d:
		ans.extend([i] * d[i])
	print(*ans)


def g_c_d(a, b):
	if a == 0:
		return b
	return g_c_d(b % a, a)
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	b = []
	b.append(max(l))
	l.remove(max(l))
	num = b[0]
	for j in range(n - 1):
		gcd = 0
		for k in range(n - j - 1):
			a = g_c_d(num, l[k])
			if a > gcd:
				x = l[k]
				gcd = a
		num = gcd
		l.remove(x)
		b.append(x)
		if x == 1:
			b += l
			break
	print(*b)


from math import gcd

def rear(a, pgcd):
	if len(a) <= 1:
		return a
	i = a.index(max(a, key=lambda x: gcd(pgcd, x)))
	(a[i], a[0]) = (a[0], a[i])
	f = []
	o = []
	pgcd = gcd(pgcd, a[0])
	[f.append(x) if gcd(x, a[0]) > 1 else o.append(x) for x in a]
	return a[0:1] + rear(f[1:], pgcd) + o
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ret = rear(a, max(a))
	gcd1 = ret[0]
	print(*ret)


from collections import defaultdict
import math
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	final = [max(l)]
	done = defaultdict(int)
	for j in range(n):
		done[l[j]] += 1
	val = final[0]
	done[final[0]] -= 1
	for j in range(1, n):
		maximum = 0
		number = 0
		for k in range(n):
			gcd = math.gcd(l[k], val)
			if done[l[k]] != 0 and gcd >= maximum:
				maximum = gcd
				number = l[k]
		final.append(number)
		done[number] -= 1
		val = maximum
	print(*final, sep=' ')


def gcd(x, y):
	while y != 0:
		(x, y) = (y, x % y)
	return x
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	ans = []
	maxI = 0
	for i in range(n):
		if a[i] > a[maxI]:
			maxI = i
	ans.append(a.pop(maxI))
	currGCD = ans[0]
	while a:
		gcd2 = 0
		maxI = 0
		for i in range(len(a)):
			if gcd(a[i], currGCD) > gcd2:
				maxI = i
				gcd2 = gcd(a[i], currGCD)
		currGCD = gcd2
		ans.append(a.pop(maxI))
	print(' '.join([str(x) for x in ans]))


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	v = [0] * n
	a.sort(reverse=True)
	b.append(max(a))
	v[0] = 1
	i = 1
	curgcd = b[-1]
	for i in range(n):
		m = -math.inf
		pos = -1
		for j in range(n):
			if v[j] == 0:
				if math.gcd(curgcd, a[j]) > m:
					pos = j
					m = math.gcd(curgcd, a[j])
		if pos != -1:
			b.append(a[pos])
			v[pos] = 1
			curgcd = math.gcd(curgcd, a[pos])
	print(*b)


def solve(g):
	m = 0
	s = 0
	for i in range(n):
		if li[i] != -1:
			if gcd(li[i], g) > m:
				s = i
			m = max(m, gcd(g, li[i]))
	r = li[s]
	g = gcd(m, g)
	li[s] = -1
	return [r, g]

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
t = int(input())
li = []
for _ in range(t):
	n = int(input())
	li = list(map(int, input().split()))
	a1 = max(li)
	g1 = a1
	ans = [a1]
	li[li.index(a1)] = -1
	for i in range(1, n):
		[r1, g1] = solve(g1)
		ans.append(r1)
	print(*ans)


import math
from collections import deque
from collections import defaultdict
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	arr = list(map(int, input().strip().split(' ')))
	arr.sort(reverse=True)
	ans = []
	m = {}
	m[0] = 1
	mx = arr[0]
	ans.append(mx)
	gd = mx
	for i in range(n):
		mxx = 0
		mxi = -1
		for j in range(n):
			if m.get(j) is not None:
				continue
			k = math.gcd(gd, arr[j])
			if k > mxx:
				mxx = k
				mxi = j
		if mxi != -1:
			ans.append(arr[mxi])
			m[mxi] = 1
			gd = math.gcd(gd, arr[mxi])
	for i in ans:
		print(i, end=' ')
	print()


from math import gcd

def find_max(pre):
	(g, to_ans) = (1, [1, arr[0]])
	for b in arr:
		tem_g = gcd(pre, b)
		if tem_g > g:
			(g, to_ans) = (tem_g, [tem_g, b])
	return to_ans
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ma = max(arr)
	(ans_gcd, ans, ans_res) = ([ma], [], [ma])
	arr.remove(ma)
	for m in range(n - 1):
		rep = find_max(ans_gcd[-1])
		ans_gcd.append(rep[0])
		arr.remove(rep[1])
		ans_res.append(rep[1])
	print(' '.join([str(x) for x in ans_res]))


from sys import stdin
import sys
import math
tt = int(stdin.readline())
for loop in range(tt):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	a.sort()
	ans = [a[-1]]
	now = a[-1]
	del a[-1]
	a.reverse()
	able = [True] * (n - 1)
	for i in range(n - 1):
		tmp = float('-inf')
		maxind = None
		for j in range(len(a)):
			if not able[j]:
				continue
			X = math.gcd(now, a[j])
			if X > tmp:
				tmp = X
				maxind = j
			if tmp > a[j]:
				break
		able[maxind] = False
		ans.append(a[maxind])
		now = tmp
	print(*ans)


def gcd(a, b):
	while a != 0 and b != 0:
		if a > b:
			a %= b
		else:
			b %= a
	return a + b
n = int(input())
for i in range(n):
	n1 = int(input())
	a = list(map(int, input().split()))
	b = [0 for i in a]
	d = [False for i in a]
	h = 0
	for i in range(len(a)):
		g = 0
		index = 0
		for j in range(len(a)):
			gcd1 = gcd(h, a[j])
			if gcd1 > g and d[j] == False:
				g = gcd1
				index = j
		h = g
		b[i] = a[index]
		d[index] = True
	print(*b)


import math
import os
import random
import re
import string
from sys import *
from collections import *

def find_gcd(x, y):
	(a, b) = (x, y)
	while y:
		(x, y) = (y, x % y)
	lcm = int(a * b / x)
	return x

def bs(arr, x, l, r):
	if l <= r:
		mid = (r + l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return bs(arr, x, l, mid - 1)
		else:
			return bs(arr, x, mid + 1, r)
	else:
		return -1

def solve():
	for _ in range(int(input())):
		n = int(input())
		l = list(map(int, stdin.readline().strip().split()))
		res = [max(l)]
		rr = max(l)
		l.remove(max(l))
		while len(l) > 0:
			ma = 0
			for j in range(len(l)):
				a = find_gcd(l[j], rr)
				if a >= ma:
					ma = a
					r = l[j]
			rr = ma
			res.append(r)
			l.remove(r)
		print(*res)
solve()


import sys
import os

def changeStdioToFile():
	path = os.path.dirname(os.path.abspath(__file__))
	sys.stdin = open(f'{path}/input.txt', 'r')
	sys.stdout = open(f'{path}/output.txt', 'w')

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = []
	a.sort(reverse=True)
	b.append(a[0])
	a.pop(0)
	newGcd = b[-1]
	while a:
		numForMaxGcd = a[0]
		maxGcd = 0
		for num in a:
			curGcd = gcd(newGcd, num)
			if maxGcd < curGcd:
				maxGcd = curGcd
				numForMaxGcd = num
		b.append(numForMaxGcd)
		a.pop(a.index(numForMaxGcd))
		newGcd = gcd(newGcd, numForMaxGcd)
	print(*b)


def gcd(a, b):
	return a if b == 0 else gcd(b, a % b)
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	m = 0
	for j in range(n):
		if len(b) == 0:
			k = max(a)
			m = k
		else:
			m0 = 0
			for x in a:
				r = gcd(x, m)
				if r > m0:
					m0 = r
					k = x
			m = m0
		b.append(k)
		a.remove(k)
	print(' '.join((str(x) for x in b)))


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	for _ in range(int(input())):
		n = int(input())
		a = sorted(list(map(int, input().split())), reverse=True)
		f = [0] * (n + 5)
		try:
			ans = [a[0]]
			f[0] = 1
			g = a[0]
			while len(ans) != n:
				mx = 0
				pos = -1
				for i in range(n):
					if f[i] == 0:
						if gcd(g, a[i]) > mx:
							mx = gcd(g, a[i])
							pos = i
				f[pos] = 1
				ans.append(a[pos])
				g = gcd(g, a[pos])
		except:
			pass
		print(' '.join(map(str, ans)))
main()


from sys import stdin, stdout
import math
from collections import Counter, deque
L = lambda : list(map(int, stdin.readline().strip().split()))
M = lambda : map(int, stdin.readline().strip().split())
I = lambda : int(stdin.readline().strip())
S = lambda : stdin.readline().strip()
C = lambda : stdin.readline().strip().split()
mod = 1000000007

def pr(a):
	print(' '.join(list(map(str, a))))

def solve():
	n = I()
	a = L()
	a.sort()
	b = [a[-1]]
	a.pop()
	bo = [0] * n
	bo[-1] = 1
	g = b[0]
	while n > len(b):
		m = 0
		ind = 0
		for i in range(n):
			if bo[i] == 0:
				k = math.gcd(g, a[i])
				if k > m:
					ind = i
					m = k
		b += [a[ind]]
		bo[ind] = 1
		g = m
	pr(b)
for _ in range(I()):
	solve()


import math

def main(A, n):
	res = []
	val = max(A)
	res.append(val)
	A.remove(val)
	pre_gcd = val
	flag = 'Notfound'
	while A != []:
		max_gcd = 0
		for i in A:
			cur_gcd = math.gcd(pre_gcd, i)
			if cur_gcd > max_gcd:
				max_gcd = cur_gcd
				val = i
				flag = 'found'
		if flag == 'Notfound':
			A.remove(i)
			res.append(i)
		else:
			A.remove(val)
			res.append(val)
			pre_gcd = max_gcd
	return res
t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	val = main(A, n)
	print(*val)


from math import gcd
from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = defaultdict(int)
	for i in a:
		d[i] += 1
	new_seq = [max(a)]
	gcd_so_far = new_seq[0]
	d[gcd_so_far] -= 1
	while len(new_seq) != n:
		this_gcd = 0
		element = None
		for i in range(n):
			if gcd(gcd_so_far, a[i]) > this_gcd and d[a[i]]:
				this_gcd = gcd(gcd_so_far, a[i])
				element = a[i]
		d[element] -= 1
		new_seq.append(element)
		gcd_so_far = gcd(gcd_so_far, element)
	print(*new_seq)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for p in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	a = max(arr)
	ans = []
	ar = []
	s = set()
	g = max(arr)
	while len(ar) < n:
		ar1 = []
		m = -1
		for d in arr:
			if d not in s and gcd(g, d) > m:
				m = gcd(g, d)
		for d in arr:
			if d not in s and gcd(g, d) == m:
				ar1.append(d)
		ar += ar1
		for d in ar1:
			s.add(d)
		g = m
	print(' '.join(list(map(str, ar))))


import math
for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	s.sort()
	g = s[-1]
	k = 0
	b = [s[n - 1]]
	s[-1] = -1
	temp = g
	for i in range(1, n):
		ma = 0
		k = 0
		for j in range(n):
			if s[j] != -1:
				if math.gcd(s[j], g) >= ma:
					k = j
					ma = math.gcd(s[j], g)
		b.append(s[k])
		g = math.gcd(g, s[k])
		s[k] = -1
	print(*b)


import math
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	mx = max(arr)
	ans = []
	gc = mx
	j = 0
	while j < len(arr):
		m_gc = 0
		m_ind = 0
		i = 0
		while i < len(arr):
			temp_gcd = math.gcd(gc, arr[i])
			if temp_gcd > m_gc:
				m_gc = temp_gcd
				m_ind = i
			i += 1
		gc = m_gc
		ans.append(arr[m_ind])
		arr.pop(m_ind)
		if gc == 1:
			ans += arr
			break
	print(*ans)


def GCD(a, b):
	if b > a:
		(a, b) = (b, a)
	while b != 0:
		a = a % b
		(a, b) = (b, a)
	return a
import sys
for _ in range(int(input())):
	n = int(sys.stdin.readline())
	arr = list(map(int, sys.stdin.readline().split()))
	ansarr = []
	k = max(arr)
	ansarr.append(k)
	arr.remove(k)
	arr = sorted(arr, reverse=True)
	while sum(arr) != 0:
		GCDMAX = []
		for i in arr:
			if i == 0:
				GCDMAX.append(0)
			else:
				GCDMAX.append(GCD(k, i))
		k = max(GCDMAX)
		for i in range(len(arr)):
			if GCDMAX[i] == k:
				ansarr.append(arr[i])
				arr[i] = 0
	print(' '.join(map(str, ansarr)))


def pfac(n):
	i = 2
	arr = []
	while i <= n:
		if n % i == 0:
			n = n // i
			arr.append(i)
		else:
			i += 1
	return arr

def gcd(a1, a2, n1, n2):
	g = 1
	i = 0
	j = 0
	while i < n1 and j < n2:
		if a1[i] == a2[j]:
			g *= a1[i]
			i += 1
			j += 1
		elif a1[i] > a2[j]:
			j += 1
		else:
			i += 1
	return g
t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(j) for j in input().split()]
	arr.sort(reverse=True)
	pf = [pfac(j) for j in arr]
	ans = [arr[0]]
	grr = pf[0]
	del pf[0]
	del arr[0]
	while len(pf) > 0:
		maxi = 0
		ind = 0
		for k in range(len(pf)):
			var = gcd(grr, pf[k], len(grr), len(pf[k]))
			if var > maxi:
				maxi = var
				ind = k
		ans.append(arr[ind])
		grr = pfac(maxi)
		del pf[ind]
		del arr[ind]
	for j in ans:
		print(j, end=' ')
	print()


import math
for mm in range(int(input())):
	n = int(input())
	b = []
	a = list(map(int, input().split(' ')))
	a.sort()
	a.reverse()
	k = int(0)
	jr = int(0)
	b.append(max(a))
	mx = max(a)
	a.remove(max(a))
	if len(a) >= 1:
		for i in range(len(a)):
			if math.gcd(mx, a[i]) > k:
				k = math.gcd(mx, a[i])
				jr = a[i]
		b.append(jr)
		a.remove(jr)
		lr = int(0)
		while len(a):
			for kk in a:
				if math.gcd(kk, k) > lr:
					lr = math.gcd(kk, k)
					jr = kk
			b.append(jr)
			a.remove(jr)
			k = lr
			lr = 0
	print(*(ja for ja in b))


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	arr = l()
	arr.sort()
	answer = [arr.pop()]
	g = answer[-1]
	while arr:
		maxi = gcd(arr[0], g)
		index = 0
		for i in range(1, len(arr)):
			if gcd(arr[i], g) > maxi:
				index = i
				maxi = gcd(arr[i], g)
		answer.append(arr[index])
		arr.pop(index)
		g = maxi
	outa(*answer)


import math, sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	A.sort(reverse=True)
	B = [A[0]]
	val = A[0]
	vis = [0 for i in range(n)]
	vis[0] = 1
	for i in range(1, n):
		ind = i
		j = 0
		while j < n and vis[j] != 0:
			j = j + 1
		val1 = math.gcd(val, A[j])
		ind = j
		k = j
		for j in range(k + 1, n):
			if vis[j] == 0:
				v1 = math.gcd(val, A[j])
				if v1 >= val1:
					val1 = v1
					ind = j
		vis[ind] = 1
		val = val1
		B.append(A[ind])
	print(*B)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [max(arr)]
	d = {max(arr): 1}
	G = ans[0]
	for _ in range(n - 1):
		t = {}
		(maxim, now) = (0, 0)
		for i in arr:
			if i in d and (i not in t or t[i] < d[i]):
				if i not in t:
					t[i] = 0
				t[i] += 1
				continue
			g = gcd(G, i)
			if g > maxim:
				maxim = g
				now = i
		ans.append(now)
		if now not in d:
			d[now] = 0
		d[now] += 1
		G = gcd(G, now)
	print(*ans)


t = int(input())

def hcf(a, b):
	if a == 0:
		return b
	return hcf(b % a, a)
while t:
	t -= 1
	n = int(input())
	a = [int(ai) for ai in input().split()]
	b = []
	b.append(max(a))
	for i in range(0, n):
		if a[i] == b[0]:
			a.pop(i)
			break
	temp = -1
	ind = -1
	gcd = b[0]
	for i in range(1, n):
		for j in range(0, len(a)):
			ans = hcf(gcd, a[j])
			if ans > temp:
				temp = ans
				ind = j
			if ans == temp:
				if a[j] > a[ind]:
					ind = j
		b.append(a[ind])
		a.pop(ind)
		temp = -1
		ind = -1
		gcd = hcf(gcd, b[i])
	for bi in b:
		print(bi, end=' ')
	print()


import sys, os
import math
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def MI():
	return map(int, input().split())

def out(var):
	sys.stdout.write(str(var) + '\n')
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	out = []
	for i in range(arr.count(arr[-1])):
		out.append(arr.pop())
	p = out[-1]
	while len(arr) != 0:
		g = 1
		todel = []
		for i in range(len(arr)):
			if math.gcd(p, arr[i]) > g:
				g = math.gcd(p, arr[i])
				todel = [i]
			elif math.gcd(p, arr[i]) == g:
				todel.append(i)
		todel.reverse()
		p = g
		for i in todel:
			out.append(arr.pop(i))
	print(*out)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d

def computeGCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
t = int(input())
for q in range(t):
	n = inputnum()
	a = inputlist()
	g = 0
	for i in range(n):
		best = 0
		for j in range(len(a)):
			if computeGCD(g, a[j]) > computeGCD(g, a[best]):
				best = j
		g = computeGCD(g, a[best])
		print(a[best], end=' ')
		a.pop(best)
	print()


from sys import stdin, stdout
from math import gcd
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	h = max(a)
	ans = []
	while 1:
		maxh = 0
		for j in range(n):
			if a[j] == -1:
				continue
			h1 = gcd(a[j], h)
			if h1 > maxh:
				maxh = h1
				ind = j
		if maxh == 0:
			break
		ans += [a[ind]]
		a[ind] = -1
		h = maxh
	print(*ans)


import math
t = int(input())
for p in range(t):
	n = int(input())
	b = list(map(int, input().split()))
	q = max(b)
	v = [0] * n
	arr = []
	res = [0]
	j = 0
	while j < n:
		if b[j] == q:
			arr.append(q)
			v[j] = 1
			break
		j += 1
	g = q
	i = 1
	while i < n:
		j = 0
		mi = 0
		while j < n:
			if v[j] == 0:
				res = math.gcd(g, b[j])
				if res > mi:
					mi = res
					pos = j
			j += 1
		g = mi
		v[pos] = 1
		arr.append(b[pos])
		i += 1
	print(*arr)


import math

class Read:

	@staticmethod
	def string():
		return input()

	@staticmethod
	def int():
		return int(input())

	@staticmethod
	def list(sep=' '):
		return input().split(sep)

	@staticmethod
	def list_int(sep=' '):
		return list(map(int, input().split(sep)))

def solve():
	n = Read.int()
	a = Read.list_int()
	l = 0
	for i in range(n):
		if a[i] > a[l]:
			l = i
	res = [str(a[l])]
	tmp = {}
	tmp[l] = 1
	t = a[l]
	for i in range(n - 1):
		m = 0
		idx = 0
		for j in range(n):
			if j in tmp:
				continue
			c = math.gcd(t, a[j])
			if c > m:
				m = c
				idx = j
		t = m
		tmp[idx] = 1
		res.append(str(a[idx]))
	print(' '.join(res))
query_count = Read.int()
while query_count:
	query_count -= 1
	solve()


def element(a, s):
	z = 0
	x = 0
	for i in range(len(s)):
		d = math.gcd(a, s[i])
		if d > z:
			z = d
			x = s[i]
	return (x, z)
import math
t = int(input())
for h in range(t):
	n1 = int(input())
	n = list(map(int, input().split()))
	s = n[:]
	new = []
	new.append(max(n))
	s.remove(new[0])
	if n1 >= 2:
		(x, z) = element(new[-1], s)
		new.append(x)
		s.remove(x)
	for i in range(n1 - 2):
		(x, z) = element(z, s)
		new.append(x)
		s.remove(x)
	print(*new)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	l.reverse()
	sol = []
	sol.append(l[0])
	g = l[0]
	del l[0]
	while len(l) > 0:
		tg = -1
		ind = -1
		for i in range(len(l)):
			ttg = gcd(g, l[i])
			if ttg > tg:
				ind = i
				tg = ttg
		g = tg
		sol.append(l[ind])
		del l[ind]
	print(' '.join([str(i) for i in sol]))


def hcf(a, b):
	if b == 0:
		return 1
	if a % b == 0:
		return b
	return hcf(b, a % b)
t = int(input())
for _ in range(t):
	n = int(input())
	list1 = list(map(int, input().strip().split()))
	x = max(list1)
	print(x, end=' ')
	list1.remove(x)
	while len(list1) != 0:
		y = 0
		for val in list1:
			temp = hcf(x, val)
			if temp > y:
				y = temp
				cur = val
		x = y
		print(cur, end=' ')
		list1.remove(cur)
	print()


import math
n = int(input())
for i in range(n):
	m = int(input())
	nums = [int(x) for x in input().split()]
	maxi = max(nums)
	maxd = max(nums)
	print(maxi, end=' ')
	for j in range(m - 1):
		nums.remove(maxi)
		temp = [math.gcd(maxd, x) for x in nums]
		maxd = max(temp)
		maxi = nums[temp.index(maxd)]
		print(maxi, end=' ')
	print()


import math
for test in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	c = []
	max_num = max(a)
	max_idx = a.index(max_num)
	c.append(max_num)
	a.pop(max_idx)
	gcd_1 = False
	curr_gcd = c[0]
	for i in range(n - 1):
		val = math.gcd(a[0], curr_gcd)
		h_idx = 0
		if gcd_1 is False:
			for (idx, j) in enumerate(a):
				value = math.gcd(j, curr_gcd)
				if value > val:
					val = value
					h_idx = idx
		curr_gcd = val
		if val == 1:
			gcd_1 = True
		if gcd_1 is True:
			max_num = max(a)
			max_idx = a.index(max_num)
			c.append(max_num)
			a.pop(max_idx)
		else:
			c.append(a[h_idx])
			a.pop(h_idx)
	for i in c:
		print(i, end=' ')
	print()


for t in range(int(input())):
	n = int(input())
	(*a,) = map(int, input().split())
	a.sort(reverse=True)
	ans = [a[0]]
	a = a[1:]
	n -= 1
	last = ans[-1]
	for i in range(last, 0, -1):
		if last % i != 0:
			continue
		for j in range(n):
			if a[j] > 0 and a[j] % i == 0:
				ans.append(a[j])
				a[j] = -1
				last = i
	for i in range(n):
		if a[i] > 0:
			ans.append(a[i])
	print(*ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
t = int(input())
for _ in range(t):
	n = int(input())
	li = [int(abs(int(i))) for i in input().split()]
	li.sort()
	g = li[-1]
	ans = [g]
	li.pop()
	d = {}
	for i in li:
		d[i] = d.get(i, 0) + 1
	s = set(li)
	while s:
		mx = 0
		cur = -1
		for i in s:
			tg = math.gcd(g, i)
			if tg > mx:
				mx = tg
				cur = i
		ans.append(cur)
		d[cur] -= 1
		g = mx
		if d[cur] == 0:
			s.discard(cur)
	print(*ans)


t = int(input())

def gcd2(a, b):
	if b > a:
		(a, b) = (b, a)
	r = a % b
	while r > 0:
		(a, b) = (b, r)
		r = a % b
	return b
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	gcd = max(a)
	a.remove(gcd)
	b = [gcd]
	while len(b) < n:
		new_gcd = 0
		new_value = 0
		for c in a:
			g = gcd2(gcd, c)
			if g > new_gcd:
				new_gcd = g
				new_value = c
		if new_gcd == 1:
			b.extend(a)
		else:
			b.append(new_value)
			gcd = new_gcd
			a.remove(new_value)
	printable = ' '.join([str(i) for i in b])
	print(printable)


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))[:n]
	maxi_index = None
	maxi = -float('inf')
	for i in range(n):
		if arr[i] > maxi:
			maxi = arr[i]
			maxi_index = i
	(arr[0], arr[maxi_index]) = (arr[maxi_index], arr[0])
	curr_gcd = arr[0]
	for i in range(n - 1):
		max_gcd = 0
		max_index = None
		for j in range(i + 1, n):
			index_gcd = gcd(curr_gcd, arr[j])
			if index_gcd > max_gcd:
				max_index = j
				max_gcd = index_gcd
		curr_gcd = max_gcd
		(arr[i + 1], arr[max_index]) = (arr[max_index], arr[i + 1])
	for i in arr:
		print(i, end=' ')
	print()


import math
for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())), reverse=True)
	n = len(a)
	v = [0] * n
	v[0] = 1
	m = -1
	c = 1
	g = a[0]
	for j in range(1, n):
		m = -1
		for i in range(j, n):
			if v[i] == 0:
				z = math.gcd(g, a[i])
				if z > m:
					m = z
					u = i
		g = m
		(a[u], a[j]) = (a[j], a[u])
	print(*a)


import sys
sys.setrecursionlimit(10 ** 6)
from collections import Counter, defaultdict as dft

def mp():
	return map(int, input().split())

def ml():
	return list(map(int, input().split()))

def solve():
	n = int(input())
	arr = ml()
	vis = [0] * (n + 5)
	arr.sort(reverse=True)
	res = []
	for p in range(10 ** 3 + 1, 0, -1):
		case = 0
		for i in range(len(res)):
			if res[i] % p != 0:
				case = 1
				break
		if case:
			continue
		for i in range(n):
			if vis[i] == 0 and arr[i] % p == 0:
				res.append(arr[i])
				vis[i] = 1
	print(*res)
t = int(input())
for _ in range(t):
	solve()


import math
for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	g = max(l)
	l1 = []
	while len(l):
		maxi = 0
		for j in range(len(l)):
			if math.gcd(g, l[j]) > maxi:
				maxi = math.gcd(g, l[j])
				c = l[j]
		g = maxi
		l.remove(c)
		l1.append(c)
	print(*l1)


from math import gcd

def read_line():
	return list(map(int, input().split()))
T = int(input())
for _ in range(T):
	n = int(input())
	l = list(reversed(sorted(read_line())))
	ans = [l[0]]
	l.remove(l[0])
	g = ans[0]
	while True:
		if len(l) == 0:
			break
		max_n = -1
		max_n_val = -1
		for k in l:
			b = gcd(g, k)
			if b > max_n:
				max_n = b
				max_n_val = k
		ans.append(max_n_val)
		l.remove(max_n_val)
		g = max_n
	print(' '.join(map(str, ans)))


import sys
import math

def f(a, n):
	a.sort(reverse=True)
	(b, vst) = ([a[0]], {0})
	d = a[0]
	while len(vst) < n:
		(gcd, next) = (1, -1)
		for i in range(len(a)):
			if i not in vst:
				if a[i] == d:
					(gcd, next) = (d, i)
					break
				tmp = math.gcd(d, a[i])
				if tmp >= gcd:
					(gcd, next) = (tmp, i)
		b.append(a[next])
		vst.add(next)
		d = gcd
	return b
t = int(sys.stdin.readline().strip())
for _ in range(t):
	n = int(sys.stdin.readline().strip())
	a = list(map(int, sys.stdin.readline().strip().split()))
	out = f(a, n)
	for i in range(n - 1):
		sys.stdout.write('%d ' % out[i])
	sys.stdout.write('%d\n' % out[-1])


from collections import deque
from collections import OrderedDict
import math
import sys
import os
import threading
import bisect
import operator
import heapq
from atexit import register
from io import BytesIO
import io
from sys import stdin, stdout
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
input = lambda : sys.stdin.readline().rstrip('\r\n')

def gdc(a, b):
	if a % b == 0:
		return b
	else:
		return gdc(b, a % b)
for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	indUsed = [0] * n
	lGDC = max(ar)
	for i in range(n):
		idx = 0
		maxGDC = 1
		for j in range(n):
			if indUsed[j] == 0:
				(a, b) = (max(ar[j], lGDC), min(ar[j], lGDC))
				temp = gdc(a, b)
				if temp >= maxGDC:
					maxGDC = temp
					idx = j
		lGDC = maxGDC
		indUsed[idx] = 1
		print(ar[idx], end=' ')
	print()
sys.exit(0)
n = int(input())
lis = list(map(int, input().split()))
answer = 0
for i in range(n):
	answer += lis[i] - 1
if n == 1:
	print(n - 1)
elif n > 32:
	print(answer)
	sys.exit(0)
lis.sort()
for i in range(2, 50000):
	localMin = 0
	for j in range(n):
		needVal = i ** j
		localMin += abs(lis[j] - needVal)
		if localMin > answer:
			break
	else:
		answer = min(localMin, answer)
print(answer)
sys.exit(0)

class Person:

	def __init__(self, name, age):
		self.name = name
		self.age = age
p1 = Person('heelo', 27)
print(help(Person))
age = 26
name = 'Swaroop'
print('Возрас {} -- {} лет'.format(name, age))
print(help(object))


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [max(a)]
	g = ans[0]
	s = set([a.index(g)])
	for _ in range(n - 1):
		(ma, mi) = (0, 0)
		for i in range(n):
			if i not in s:
				k = gcd(g, a[i])
				if k > ma:
					mi = i
					ma = k
		g = ma
		ans.append(a[mi])
		s.add(mi)
	print(*ans)


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split(' ')))
		if n == 1:
			print(a[0])
		elif n == 2:
			print(max(a[0], a[1]), min(a[0], a[1]))
		else:
			aa = max(a)
			a.remove(aa)
			ans = [aa]
			currgcd = aa
			while currgcd != 1 and len(a) > 0:
				temp = 1
				curindex = 0
				for x in range(len(a)):
					if temp < math.gcd(currgcd, a[x]):
						temp = math.gcd(currgcd, a[x])
						curindex = x
				currgcd = temp
				ans.append(a[curindex])
				a.pop(curindex)
				if temp == 1:
					for x in range(len(a)):
						ans.append(a[x])
					break
			print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
from math import gcd
input = lambda : sys.stdin.readline().rstrip('\r\n')

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	(b, g) = ([], 0)
	while a:
		take = max(a, key=lambda i: gcd(i, g))
		b.append(take)
		g = gcd(g, take)
		a.remove(take)
	print(*b)
for _ in range(int(input())):
	solve()


def inp():
	return list(map(int, input().split()))

def get_gcd(a, b):
	if a == 0:
		return b
	return get_gcd(b % a, a)

def get_divs(n):
	cnt = 1
	res = []
	while cnt ** 2 <= n:
		if n % cnt == 0:
			res.append(cnt)
			res.append(n // cnt)
		cnt += 1
	return res

def get_val(val, arr):
	gcd_ = 0
	ind = 0
	for i in range(len(arr)):
		nw = get_gcd(a[i], val)
		if nw > gcd_:
			ind = i
			gcd_ = nw
	ret = gcd_
	vl = a[ind]
	a.pop(ind)
	return (ret, a, vl)
for t in range(int(input())):
	n = int(input())
	a = inp()
	mx = max(a)
	res = []
	while len(res) < n:
		(mx, a, vl) = get_val(mx, a)
		res.append(vl)
	print(*res)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	used = [False for i in range(n)]
	a.sort(reverse=True)
	g = a[0]
	used[0] = True
	print(a[0], end=' ')
	while g != 1:
		mx = 1
		ind = -1
		for i in range(0, n):
			if used[i] == False:
				if gcd(g, a[i]) > mx:
					mx = gcd(g, a[i])
					ind = i
		if ind > -1:
			used[ind] = 1
			g = gcd(g, a[ind])
			print(a[ind], end=' ')
		else:
			break
	for i in range(n):
		if used[i] == False:
			print(a[i], end=' ')
	print()


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class smt:

	def __init__(self, l, r, arr):
		self.l = l
		self.r = r
		self.value = (1 << 31) - 1 if l < r else arr[l]
		mid = (l + r) // 2
		if l < r:
			self.left = smt(l, mid, arr)
			self.right = smt(mid + 1, r, arr)
			self.value &= self.left.value & self.right.value

	def setvalue(self, x, val):
		if self.l == self.r:
			self.value = val
			return
		mid = (self.l + self.r) // 2
		if x <= mid:
			self.left.setvalue(x, val)
		else:
			self.right.setvalue(x, val)
		self.value = self.left.value & self.right.value

	def ask(self, l, r):
		if l <= self.l and r >= self.r:
			return self.value
		val = (1 << 31) - 1
		mid = (self.l + self.r) // 2
		if l <= mid:
			val &= self.left.ask(l, r)
		if r > mid:
			val &= self.right.ask(l, r)
		return val

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [(ch, len(list(g))) for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None
t = N()
for i in range(t):
	n = N()
	a = RLL()
	ans = []
	c = Counter(a)
	ma = max(a)
	ans.append(ma)
	c[ma] -= 1
	cur = ma
	for i in range(n - 1):
		res = []
		for j in range(2, int(sqrt(cur)) + 1):
			if cur % j == 0:
				res.append(j)
				if j * j != cur:
					res.append(cur // j)
		res.append(cur)
		res.sort(reverse=True)
		flag = False
		for k in res:
			for j in range(k, ma + 1, k):
				if c[j] > 0:
					c[j] -= 1
					ans.append(j)
					cur = k
					flag = True
					break
			if flag:
				break
		if not flag:
			break
	for x in a:
		if c[x] > 0:
			ans += [x] * c[x]
			c[x] = 0
	print(*ans)


import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda : int(input())
li = lambda : list(map(int, input().split()))

def solve():
	n = I()
	a = li()
	p = max(a)
	ans = []
	q = deque()
	a.sort(reverse=True)
	ans = [a[0]]
	p = a[0]
	visited = [0] * n
	visited[0] = 1
	while len(ans) != n:
		p = math.gcd(p, ans[-1])
		m = 0
		key = -1
		for i in range(n):
			if visited[i]:
				continue
			g = math.gcd(p, a[i])
			if g > m:
				m = g
				key = i
		if key != -1:
			ans.append(a[key])
			visited[key] = 1
	print(*ans)
for _ in range(I()):
	solve()


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = mpos(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def graph(n, m):
	adj = dict()
	for i in range(1, n + 1):
		adj.setdefault(i, 0)
	for i in range(m):
		(a, b) = map(int, input().split())
		adj[a] += 1
		adj[b] += 1
	return adj
import sys
import threading
from math import *
sys.setrecursionlimit(300000)
threading.stack_size(10 ** 8)

def pow_of_3(x):
	ans = 0
	while x % 3 == 0:
		ans += 1
		x //= 3
	return ans
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(*a)
	else:
		a.sort()
		ans = [a[-1]]
		gg = a[-1]
		vis = [0] * n
		vis[-1] = 1
		ind = n - 1
		for i in range(n - 1, -1, -1):
			if vis.count(1) == n:
				break
			li = [0] * n
			for j in range(n - 1, -1, -1):
				li[j] = gcd(gg, a[j])
				if vis[j] == 1:
					li[j] = 0
			gg = max(li)
			ind = li.index(gg)
			ans.append(a[ind])
			vis[ind] = 1
		print(*ans)


t = int(input())

def gcd(a, b):
	if a < b:
		(a, b) = (b, a)
	if a % b == 0:
		return b
	if a == 1 or b == 1:
		return 1
	return gcd(b, a % b)
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	first = max(a)
	answer = [first]
	done = set()
	max_index = 0
	for i in range(0, len(a)):
		if a[i] == first:
			max_index = i
			break
	done.add(max_index)
	i = 1
	gcd_value = first
	check = gcd_value
	while i < n:
		maximum = 0
		max_val = 0
		for k in range(0, len(a)):
			if k in done:
				continue
			if gcd(check, a[k]) > maximum:
				maximum = gcd(check, a[k])
				max_val = a[k]
				max_index = k
		check = gcd(check, max_val)
		answer.append(max_val)
		done.add(max_index)
		i += 1
	print(*answer)


def gcd(a, b):
	if a >= b:
		if a % b == 0:
			return b
		else:
			return gcd(a % b, b)
	elif b % a == 0:
		return a
	else:
		return gcd(a, b % a)

def fun(c, l):
	t = 1
	p = 0
	for i in l:
		v = gcd(i, c)
		if v > t:
			t = v
			p = i
	return [p, t]
for _ in range(int(input())):
	n = int(input())
	l = list(sorted(list(map(int, input().split()))))
	c = l[-1]
	l.pop()
	m = [c]
	for i in range(n - 1):
		u = fun(c, l)
		k = u[0]
		c = u[1]
		if k:
			m.append(k)
			l.remove(k)
		else:
			m += l
			break
	print(*m, sep=' ')


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for i in ' ' * int(input()):
	n = int(input())
	L = list(map(int, input().split()))
	M = [0]
	MM = []
	check = [False] * n
	for i in range(n):
		ct = 0
		pt = -1
		for j in range(n):
			if not check[j]:
				k = gcd(M[-1], L[j])
				if k > ct:
					ct = k
					pt = j
		M.append(ct)
		MM.append(pt)
		check[pt] = True
	for j in MM:
		print(L[j], end=' ')
	print()


import sys, math
try:
	(sys.stdin, sys.stdout) = (open('input.txt', 'r'), open('out.txt', 'w'))
except:
	pass
from sys import stdin, stdout
mod = int(1000000000.0 + 7)
from statistics import mode
from collections import *
from math import ceil, floor, inf, factorial, gcd, log2, sqrt, log
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()

def lcm(a, b):
	return a * b // gcd(a, b)

def setbits(n):
	return bin(n).count('1')

def resetbits(n):
	return bin(n).count('0')

def modinv(n, p):
	return pow(n, p - 2, p)

def ncr(n, r):
	(num, den) = (1, 1)
	r = min(n, n - r)
	for i in range(r):
		num *= n - i
		den *= i + 1
	return num // den

def ncr_p(n, r, p):
	(num, den) = (1, 1)
	r = min(r, n - r)
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * modinv(den, p) % p

def isPrime(num):
	if num <= 1:
		return False
	if num == 2 or n == 3:
		return True
	if num % 2 == 0 or num % 3 == 0:
		return False
	m = int(num ** 0.5) + 1
	for i in range(5, m, 6):
		if num % i == 0 or num % (i + 2) == 0:
			return False
	return True

def bin_search(s, low, high, val):
	while low <= high:
		mid = low + (high - low) // 2
		if s[mid] == val:
			return mid
		elif s[mid] < val:
			low = mid + 1
		else:
			high = mid - 1
	return -1

def sumofdigit(num):
	count = 0
	while num:
		count += num % 10
		num //= 10
	return count

def inputmatrix():
	(r, c) = iia()
	mat = [0] * r
	for i in range(r):
		mat[i] = iia()
	return (r, c, mat)

def prefix_sum(n, s):
	for i in range(1, n):
		s[i] += s[i - 1]
	return s

def binomial(n, k):
	if 0 <= k <= n:
		ntok = 1
		ktok = 1
		for t in range(1, min(k, n - k) + 1):
			ntok *= n
			ktok *= t
			n -= 1
		return ntok // ktok
	else:
		return 0

def divisors(n):
	res = []
	for i in range(1, ceil(sqrt(n)) + 1):
		if n % i == 0:
			if i == n // i:
				res.append(i)
			else:
				res.append(i)
				res.append(n // i)
	return res
for _ in range(ii1()):
	n = ii1()
	arr = iia()
	arr.sort(reverse=True)
	ans = []
	ans.append(arr[0])
	curr = arr[0]
	flag = [False] * n
	flag[0] = True
	now_gcd = -inf
	for i in range(1, n):
		now_gcd = -inf
		for j in range(n):
			if flag[j] == False:
				now = gcd(curr, arr[j])
				if now > now_gcd:
					now_gcd = now
					index = j
		flag[index] = True
		ans.append(arr[index])
		curr = now_gcd
	print(*ans)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil, pi, sin, cos, acos, atan
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = ip()
for _ in range(t):
	n = ip()
	arr = list(inp())
	ans = [max(arr)]
	sam = ans[0]
	arr.remove(max(arr))
	while arr:
		dic = {}
		n = len(arr)
		for i in range(n):
			test = gcd(sam, arr[i])
			dic[test] = i
		ch = max(list(dic.keys()))
		pos = dic[ch]
		sam = gcd(ch, sam)
		ans.append(arr[pos])
		del arr[pos]
	print(*ans)


from collections import deque
import sys
from functools import reduce

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))), reverse=True)

def main():
	t = Iint()
	for _ in range(t):
		n = Iint()
		a = Ilist()
		a.sort(reverse=True)
		b = [0] * n
		b[0] = max(a)
		a[0] = -1
		prev = b[0]
		for i in range(1, n):
			debug(b, c=1)
			f = factors(prev)
			debug(f, c=3)
			for fi in f:
				debug(a, fi)
				for j in range(n):
					if a[j] != -1 and a[j] % fi == 0:
						b[i] = a[j]
						a[j] = -1
						prev = fi
						break
				else:
					continue
				break
		Plist(b)
en = enumerate
FIO = 10

def debug(*args, c=6):
	pass
BUFSIZE = 8 * 1024

def Istr():
	return input()

def Iint():
	return int(input())

def Ilist():
	return list(map(int, input().split()))

def Imap():
	return map(int, input().split())

def Plist(li, s=' '):
	print(s.join(map(str, li)))
if not FIO:
	if __name__ == '__main__':
		main()
		exit()
else:
	from io import BytesIO, IOBase
	import os

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


from math import gcd
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	for i in range(len(a)):
		a[i] = [a[i], a[i]]
	for i in range(n):
		maxi = [0, 0]
		for i in a:
			if maxi[0] < i[0]:
				maxi = i
		print(maxi[1], end=' ')
		for i in range(len(a)):
			if a[i][0] != 0:
				a[i][0] = gcd(maxi[0], a[i][0])
		for i in range(len(a)):
			if a[i][0] == maxi[0]:
				a[i][0] = 0
				break
	print()


import os, sys
from io import BytesIO, IOBase
from collections import Counter
from math import gcd

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = sorted(map(int, input().split()), reverse=1)
		x = Counter(arr)
		x[arr[0]] -= 1
		lst = [arr[0]]
		cul = arr[0]
		while len(lst) != n:
			maxi = -1
			ans = -1
			for i in x:
				if x[i]:
					xx = gcd(i, cul)
					if xx > maxi:
						maxi = xx
						ans = i
			x[ans] -= 1
			lst.append(ans)
			cul = gcd(cul, ans)
		for i in lst:
			print(i, end=' ')
		print('')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	c = [arr[0]]
	gc = arr[0]
	se = set()
	se.add(0)
	for i in range(1, n):
		ma = 0
		for j in range(n):
			if gcd(gc, arr[j]) > ma and j not in se:
				ma = gcd(gc, arr[j])
				ans = arr[j]
				k = j
		se.add(k)
		c.append(ans)
		gc = gcd(gc, c[i])
	print(*c)


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for i in range(t):
	n = iinput()
	a = rlinput()
	done = [False] * n
	maxx = max(a)
	less = float('inf')
	lst = []
	while len(lst) != n:
		curridx = -1
		currmax = 0
		currgcd = 1
		for i in range(n):
			gcd = math.gcd(a[i], maxx)
			if gcd >= currgcd and (not done[i]):
				currmax = a[i]
				curridx = i
				currgcd = gcd
		lst.append(currmax)
		done[curridx] = True
		maxx = currgcd
	print(*lst)


import math
tst = int(input())
t = 1
while t <= tst:
	n = int(input())
	ls = list(map(int, input().split()))
	pos = ls.index(max(ls))
	ans = []
	d = max(ls)
	ls1 = [0] * (max(ls) + 4)
	ans.append(max(ls))
	ls1[pos] = 1
	i = 1
	while i < n:
		pos = -1
		g = 0
		j = 0
		while j < len(ls):
			if ls1[j] != 1 and math.gcd(ls[j], d) > g:
				g = math.gcd(ls[j], d)
				pos = j
			j += 1
		ans.append(ls[pos])
		ls1[pos] = 1
		d = g
		i += 1
	i = 0
	while i < n:
		print(ans[i], end=' ')
		i += 1
	print('\r')
	t += 1


from math import gcd
for _ in range(int(input())):
	x = int(input())
	(*li,) = map(int, input().split())
	a = max(li)
	li.remove(a)
	hcf = a
	li1 = [a]
	for i in range(x - 1):
		(m, q) = (0, 0)
		for j in li:
			if m < gcd(hcf, j):
				m = gcd(hcf, j)
				q = j
		li1 += [q]
		li.remove(q)
		hcf = m
	print(*li1)


from math import log2, ceil

def readGenerator():
	while True:
		tokens = input().split(' ')
		for t in tokens:
			yield t
reader = readGenerator()

def readWord():
	return next(reader)

def readInt():
	return int(next(reader))

def readFloat():
	return float(next(reader))

def readLine():
	return input()

def solve(a):
	a = list(reversed(sorted(a)))
	b = [a[0]]
	u = [False] * len(a)
	u[0] = True
	g = a[0]
	for i in range(len(a) - 1):
		max = -1
		pos = -1
		for j in range(0, len(a)):
			if not u[j]:
				gc = gcd(g, a[j])
				if gc > max:
					max = gc
					pos = j
		g = gcd(g, a[pos])
		b.append(a[pos])
		u[pos] = True
	return ' '.join(map(str, b))

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
tests = readInt()
for i in range(tests):
	n = readInt()
	a = [readInt() for _ in range(n)]
	print(solve(a))


for i in range(int(input())):
	from math import gcd
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	li = []
	li.append(arr.pop())
	hcf = li[-1]
	while len(arr) > 0:
		(m, q) = (0, 0)
		for x in arr:
			if m < gcd(hcf, x):
				m = gcd(hcf, x)
				q = x
		li += [q]
		arr.remove(q)
		hcf = m
	print(*li)


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
int1 = lambda x: int(x) - 1
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))
ilelec = lambda : map(int1, input().split())
alelec = lambda : list(map(int1, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	n = int(input())
	A = alele()
	A.sort()
	Ans = []
	Ans.append(A.pop())
	gc = Ans[0]
	while A:
		m = -1
		y = -1
		for i in A:
			x = math.gcd(i, gc)
			if x > m:
				m = x
				y = i
		Ans.append(y)
		A.remove(y)
		gc = math.gcd(y, gc)
		if m == 1:
			break
	Ans += A
	print(*Ans)


def nod(a, b):
	while b != 0:
		(a, b) = (b, a % b)
	return a
t = int(input())
for sdfhyujkl in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	m = max(l)
	l.pop(l.index(m))
	answer = [m]
	fifa = m
	for i in range(1, n):
		r = 0
		ind = 0
		for j in range(len(l)):
			e = nod(l[j], fifa)
			if e > r:
				r = e
				ind = j
		if r == 1:
			break
		fifa = r
		answer.append(l.pop(ind))
	answer += l
	print(*answer)


from math import *
from collections import *
for u in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	g = l[-1]
	d = [l[-1]]
	l = l[:-1]
	while len(l) > 0:
		(x, y) = (0, 0)
		for i in l:
			if gcd(i, g) > x:
				x = gcd(i, g)
				y = i
		g = gcd(g, x)
		d.append(y)
		l.remove(y)
	print(*d)


import math

def ans():
	N = int(input())
	for i in range(N):
		A = int(input())
		arr = sorted(list(map(int, input().split())))
		c = []
		arr = arr[::-1]
		c += [int(arr[0])]
		while len(arr) > 0:
			a = 0
			e = 0
			for j in range(len(arr)):
				if math.gcd(arr[j], c[-1]) > a:
					a = math.gcd(arr[j], c[-1])
					e = j
			c += [a]
			if len(arr) != 1:
				print(arr[e], end=' ')
			else:
				print(arr[e])
			arr.remove(arr[e])
ans()


import math

def maxAndInde(a):
	inde = 0
	maxim = a[0]
	for i in range(len(a)):
		if maxim < a[i]:
			inde = i
			maxim = a[i]
	return (maxim, inde)
T = int(input())
ret = []
for t in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	raw = [a[i] for i in range(len(a))]
	gc = 0
	ans = []
	while len(a) > 0:
		(maxim, inde) = maxAndInde(a)
		ans.append(raw[inde])
		a.pop(inde)
		raw.pop(inde)
		gc = math.gcd(gc, maxim)
		for i in range(len(a)):
			a[i] = math.gcd(gc, a[i])
	ret.append(ans)
for t in range(T):
	print(' '.join(list(map(str, ret[t]))))


def bigVova(arr):
	res = [None for _ in arr]
	visited = [False for _ in arr]
	d = 0
	for i in range(len(arr)):
		maxItem = 0
		index = 0
		for j in range(len(arr)):
			currGcd = gcd(d, arr[j])
			if visited[j] == False and currGcd > maxItem:
				maxItem = currGcd
				index = j
		d = maxItem
		res[i] = arr[index]
		visited[index] = True
	return res

def gcd(a, b):
	while b > 0:
		rem = a % b
		a = b
		b = rem
	return a
for i in range(int(input())):
	N = int(input())
	arr = [int(val) for val in input().split(' ')]
	print(' '.join((str(x) for x in bigVova(arr))))


import sys
input = sys.stdin.readline

def gcd(a: int, b: int) -> int:
	while b:
		(a, b) = (b, a % b)
	return a
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a, reverse=True)
	used = [False] * n
	(max_, ind) = (0, -1)
	ans = []
	for i in range(n):
		if max_ < a[i]:
			max_ = a[i]
			ind = i
	ans.append(a[ind])
	used[ind] = True
	gcd_ = a[ind]
	for _ in range(n - 1):
		max_ = -1
		ind = -1
		for j in range(n):
			if used[j]:
				continue
			tmp = gcd(gcd_, a[j])
			if max_ < tmp:
				max_ = tmp
				ind = j
		ans.append(a[ind])
		used[ind] = True
		gcd_ = max_
	print(*ans)


import math
c = int(input())
for _ in range(c):
	length = int(input())
	arr = [int(item) for item in input().split()]
	new_arr = []
	for (index, val) in enumerate(arr):
		new_arr.append((val, index))

	def reArrange(arr):
		n = len(arr)
		if n == 0:
			return []
		g_list = sorted(arr, reverse=True)
		top = g_list[0][0]
		stop_index = 0
		result_list = []
		while len(g_list) != 0:
			while stop_index + 1 <= len(g_list) - 1 and g_list[stop_index][0] == g_list[stop_index + 1][0]:
				stop_index += 1
			result_list += sorted([arr[i[1]][0] for i in g_list[:stop_index + 1]], reverse=True)
			g_list = g_list[stop_index + 1:]
			if len(g_list) == 0:
				break
			t_list = []
			for count in range(len(g_list)):
				p = math.gcd(top, g_list[count][0])
				t_list.append((p, g_list[count][1]))
			g_list = sorted(t_list, reverse=True)
			top = g_list[0][0]
			stop_index = 0
		return result_list
	print(*reArrange(new_arr))


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial
from collections import deque
from bisect import bisect_left

def gcd(a, b):
	while a % b != 0:
		(a, b) = (b, a % b)
	return b
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = {}
	ma = 0
	ans = []
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
		ma = max(ma, i)
	ans.append(ma)
	d[ma] -= 1
	if d[ma] == 0:
		d.pop(ma)
	x = ma
	for i in range(n - 1):
		ma = 0
		f = 0
		for i in d:
			t = gcd(max(x, i), min(x, i))
			if t > ma:
				ma = t
				f = i
		ans.append(f)
		x = ma
		d[f] -= 1
		if d[f] == 0:
			d.pop(f)
	print(*ans)


import sys
import math
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().rstrip().split()))
	lg = 0
	ans = []
	for t in range(n):
		(l, li, g) = (0, None, None)
		for (i, v) in enumerate(a):
			if v == 0:
				continue
			g = math.gcd(lg, v)
			if g > l:
				(l, li) = (g, i)
		lg = l
		ans.append(a[li])
		a[li] = 0
	print(' '.join(map(str, ans)))


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = sorted(list(map(int, input().split())), reverse=True)
	prev_gcd = a[0]
	for i in range(1, n):
		max_gcd = 0
		m = i
		for j in range(i, n):
			if gcd(prev_gcd, a[j]) > max_gcd:
				m = j
				max_gcd = gcd(prev_gcd, a[j])
		(a[i], a[m]) = (a[m], a[i])
		prev_gcd = gcd(prev_gcd, a[i])
	print(' '.join(map(str, a)))


import itertools
import math
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	ans = arr[0]
	for k in range(1, n):
		for kk in range(k + 1, n):
			if math.gcd(arr[k], ans) < math.gcd(arr[kk], ans):
				(arr[k], arr[kk]) = (arr[kk], arr[k])
		ans = math.gcd(ans, arr[k])
	print(*arr)


from math import gcd
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	ans = list()
	ans.append(max(a))
	cg = max(a)
	a[a.index(max(a))] = 0
	na = 0
	z = -1
	for _ in range(n):
		na = 0
		bg = 1
		for j in range(n):
			if not a[j]:
				continue
			if gcd(cg, a[j]) >= bg:
				na = a[j]
				z = j
				bg = gcd(cg, a[j])
		if not na:
			continue
		else:
			ans.append(a[z])
			cg = gcd(cg, a[z])
			a[z] = 0
	for i in range(n):
		if a[i]:
			ans.append(a[i])
	print(*ans)


from math import gcd
for _ in ' ' * int(input()):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(*a)
	elif n == 2:
		print(max(a), min(a))
	else:
		a.sort()
		x = a[-1]
		a[-1] = -1
		cnt = 0
		print(x, end=' ')
		ind = 0
		g = 0
		while True:
			if cnt == n - 1:
				break
			for i in range(n):
				if a[i] != -1:
					if gcd(x, a[i]) >= g:
						xx = a[i]
						ind = i
						g = gcd(x, a[i])
			print(xx, end=' ')
			cnt += 1
			x = gcd(x, a[ind])
			a[ind] = -1
			g = 0
			ind = 0
		print()


from math import gcd
for j in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = [0] * n
	l = 0
	for i in range(n):
		if a[i] > a[l]:
			l = i
	ans = []
	ans.append(a[l])
	s[l] = 1
	u = ans[0]
	y = 0
	for i in range(1, n):
		while s[y] == 1 and y < n:
			y += 1
		h = y
		for z in range(h + 1, n):
			if gcd(a[h], u) < gcd(a[z], u) and s[z] == 0:
				h = z
		s[h] = 1
		ans.append(a[h])
		u = gcd(u, a[h])
	print(*ans)


import math
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	t = []
	t.append(a[-1])
	x = a.pop()
	a.reverse()
	while len(a) > 0:
		y = -1
		g = -1
		for j in range(len(a)):
			if g < math.gcd(x, a[j]):
				y = j
				g = math.gcd(x, a[j])
		t.append(a[y])
		x = math.gcd(x, a.pop(y))
	ans.append(' '.join(map(str, t)))
for l in ans:
	print(l)


from collections import defaultdict
import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = defaultdict(int)
	ans = [max(l)]
	gcd = max(l)
	for i in l:
		d[i] += 1
	d[max(l)] -= 1
	curr = 1
	for i in range(n - 1):
		ele = 1
		curr = 1
		for j in l:
			if d[j] > 0:
				x = math.gcd(gcd, j)
				if x >= curr:
					curr = x
					ele = j
		d[ele] -= 1
		gcd = curr
		ans.append(ele)
		if gcd == 1:
			break
	if gcd == 1:
		for i in l:
			if d[i] > 0:
				ans.append(i)
				d[i] -= 1
	print(*ans)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	gc = a[0]
	for i in range(1, n):
		gc = math.gcd(gc, a[i])
	ans = []
	ind = a.index(max(a))
	ans.append(a.pop(ind))
	pos = ans[0]
	y = pos
	while a:
		while y >= gc:
			tf = False
			for i in range(len(a)):
				if math.gcd(a[i], pos) == y:
					pos = y
					ans.append(a[i])
					a.pop(i)
					tf = True
					break
			if tf == False:
				y -= 1
			if len(a) == 0:
				break
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	arr = sorted(list(map(int, input().split())), reverse=1)
	ans = [arr.pop(0)]
	from math import gcd
	g = gcd(ans[0], ans[0])
	while arr:
		p = 0
		for i in range(len(arr)):
			if gcd(g, arr[i]) > gcd(g, arr[p]):
				p = i
		g = gcd(arr[p], g)
		ans.append(arr.pop(p))
	print(*ans)


def ucln(a, b):
	if a < b:
		(a, b) = (b, a)
	while b > 0:
		cd = a % b
		a = b
		b = cd
	return a
t = int(input())
for ii in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort(reverse=True)
	uc = 0
	maxx = 0
	pos = 0
	b = [a[0]]
	c = [a[0]]
	f = [False] + (n - 1) * [True]
	for i in range(1, n):
		maxx = 0
		pos = 0
		for j in range(n):
			if f[j]:
				uc = ucln(c[i - 1], a[j])
				if maxx < uc:
					maxx = uc
					pos = j
		f[pos] = False
		c.append(maxx)
		b.append(a[pos])
	for i in b:
		print(i, end=' ')
	print()


ll = lambda : map(int, input().split())
t = lambda : int(input())
ss = lambda : input()
from math import log10, log2, ceil, factorial as f, gcd
for _ in range(t()):
	n = t()
	a = list(ll())
	d = [0] * n
	temp = max(a)
	d[a.index(temp)] = 1
	l = []
	l.append(temp)
	for i in range(n):
		temp1 = 0
		fx = -1
		for j in range(n):
			if d[j] == 0 and gcd(temp, a[j]) > temp1:
				temp1 = gcd(temp, a[j])
				fx = j
		if fx != -1:
			d[fx] = 1
			l.append(a[fx])
			temp = temp1
	print(*l)


import math
for ad in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	l.reverse()
	x = [l[0]]
	gc = l.pop(0)
	high = 0
	ind = -1
	for i in range(n - 1):
		for j in range(n - i - 1):
			g = math.gcd(gc, l[j])
			if g > high:
				ind = j
				high = g
		if ind != -1:
			y = l.pop(ind)
			x.append(y)
			gc = high
			ind = -1
			high = 0
	x += l
	for i in x:
		print(i, end=' ')
	print()


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	b = [a[0]]
	a.remove(a[0])
	g = b[0]
	i = 0
	while i < n - 1:
		res = 0
		val = 0
		for j in range(len(a)):
			x = math.gcd(g, a[j])
			if x >= res:
				res = x
				val = a[j]
		b.append(val)
		g = res
		a.remove(val)
		i += 1
	print(*b)


import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	m = max(l)
	g = m
	p = [m]
	visited = set()
	d = l.index(m)
	visited.add(d)
	j = 0
	while j < len(l) - 1:
		i = 0
		a = -1
		r = -1
		while i < len(l):
			if i not in visited:
				s = math.gcd(l[i], g)
				if s >= a:
					a = s
					r = i
			i = i + 1
		j = j + 1
		g = a
		visited.add(r)
		p.append(l[r])
	print(*p)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [max(l)]
	ind = l.index(max(l))
	l = l[:ind] + l[ind + 1:]
	cnt = 1
	g = ans[0]
	while cnt < n:
		ind = -1
		temp = -float('inf')
		for i in range(n - cnt):
			t = gcd(g, l[i])
			if t > temp:
				temp = t
				ind = i
		g = temp
		cnt += 1
		ans.append(l[ind])
		l = l[:ind] + l[ind + 1:]
	print(*ans)


def gcd(a, b):
	while b != 0:
		(a, b) = (b, a % b)
	return a
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l = sorted(l)
	l.reverse()
	a = [l[0]]
	g = l[0]
	mx = -100000
	m = 0
	del l[0]
	for j in range(n - 1):
		for i in range(len(l)):
			te = gcd(g, l[i])
			if te > mx:
				mx = te
				m = i
		a.append(l[m])
		g = mx
		del l[m]
		mx = -1000000
	for i in a:
		print(i, end=' ')
	print()


def gcd(a, b):
	if a < 0 or b < 0:
		return -1
	if b == 0:
		return a
	if a < b:
		(a, b) = (b, a)
	return gcd(b, a % b)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = [0] * n
	maxx = max(arr)
	for i in range(n):
		temp[i] = gcd(maxx, arr[i])
	index = 0
	ans = []
	used = [1] * n
	var = maxx
	for i in range(n):
		val = 0
		for j in range(n):
			if gcd(var, temp[j]) > val and used[j]:
				index = j
				val = gcd(var, temp[j])
		var = val
		used[index] = 0
		ans.append(index)
	for i in ans:
		print(arr[i], end=' ')
	print()


import math
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = 0
	m = (-1, -1)
	v = n
	q = []
	for k in range(n):
		m = (-1, -1)
		for j in range(v):
			p = (math.gcd(a[j], res), j)
			if p[0] > m[0]:
				m = p
		q.append(a[m[1]])
		res = m[0]
		del a[m[1]]
		v = v - 1
	print(' '.join(map(str, q)))


def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = list()
	v = [0] * n
	m = max(a)
	v[a.index(m)] = 1
	b.append(m)
	d = m
	for i in range(n):
		r = 0
		k = 0
		for j in range(n):
			if v[j] == 1:
				continue
			elif gcd(d, a[j]) > k:
				r = j
				k = gcd(d, a[j])
		d = k
		v[r] = 1
		b.append(a[r])
	print(' '.join(map(str, b[:n])))


import math
from collections import Counter
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	maa = max(l)
	c = Counter(l)
	l = list(set(l))
	a = l.index(maa)
	l[a] = 0
	gc = maa
	for i in range(c[gc]):
		print(gc, end=' ')
	m = 0
	e = 0
	ind = -1
	f = 0
	cn = 0
	while 1:
		for i in range(len(l)):
			if l[i] != 0:
				k = math.gcd(l[i], gc)
				if k > m:
					m = k
					e = l[i]
					ind = i
		if m == 1:
			f = 1
			break
		else:
			for i in range(c[e]):
				print(e, end=' ')
			cn += 1
			if cn == len(l):
				break
			gc = m
			l[ind] = 0
			ind = -1
			m = 0
			e = 0
	if f == 1:
		for i in range(len(l)):
			if l[i] != 0:
				for j in range(c[l[i]]):
					print(l[i], end=' ')
		print()
	else:
		print()


import math, sys
from collections import defaultdict, Counter, deque
from functools import reduce
INF = float('inf')
MOD = int(1000000000.0) + 7

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def isPrime(n):
	if n <= 1:
		return False
	i = 2
	while i ** 2 <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def primeFactors(n):
	factors = defaultdict(int)
	i = 2
	while i ** 2 <= n:
		while n % i == 0:
			factors[i] += 1
			n //= i
		i += 1
	if n > 1:
		factors[n] += 1
	return factors

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def vars():
	return map(int, input().split())

def array():
	return list(map(int, input().split()))

def main():
	n = int(input())
	arr = array()
	maxi = max(arr)
	ans = []
	while arr:
		(curr, val) = (0, None)
		for num in arr:
			g = gcd(maxi, num)
			if g > curr:
				curr = g
				val = num
		maxi = curr
		ans.append(val)
		arr.remove(val)
	print(*ans)
t = 1
t = int(input())
for _ in range(t):
	main()


t = int(input())
import math

def solve():
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	ans = []
	ans.append(a[n - 1])
	del a[n - 1]
	curg = ans[0]
	while len(a):
		ma = 0
		inl = 0
		flag = 0
		curm = 1
		for i in range(len(a)):
			if math.gcd(curg, a[i]) > curm:
				ma = a[i]
				inl = i
				curm = math.gcd(curg, a[i])
				flag += 1
		if flag == 0:
			break
		else:
			ans.append(ma)
			del a[inl]
			curg = math.gcd(curg, ans[-1])
	ans += a
	print(*ans, sep=' ')
while t:
	t -= 1
	solve()


import math
import sys
import collections
import bisect
import time

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	n = int(input())
	arr = get_list()
	maxim = max(arr)
	ans = [maxim]
	prev = maxim
	visted = [False] * n
	pos = arr.index(maxim)
	visted[pos] = True
	while len(ans) < n:
		pos = 0
		maxim_gcd = 1
		for i in range(n):
			if visted[i] == True:
				continue
			gcd = math.gcd(prev, arr[i])
			if gcd > maxim_gcd:
				maxim_gcd = gcd
				pos = i
		if maxim_gcd == 1:
			break
		ans.append(arr[pos])
		prev = math.gcd(arr[pos], prev)
		visted[pos] = True
	for i in range(n):
		if visted[i] == False:
			ans.append(arr[i])
	print(*ans)


from sys import *
from math import *
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	a.sort()
	b = [a[n - 1]]
	x = a[n - 1]
	a.pop()
	while a:
		y = 0
		i = 0
		for j in range(len(a)):
			m = gcd(x, a[j])
			if m > y:
				i = j
				y = m
		x = y
		b.append(a[i])
		a.pop(i)
	print(*b)


def remove(e, ind, arr):
	f = arr[:ind + 1]
	s = arr[ind + 1:]
	s.remove(e)
	return f + s

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	elem = max(a)
	a.remove(elem)
	a.insert(0, elem)
	ans = [elem]
	i = 0
	while i < n - 1:
		mx = 1
		tp = a[i + 1]
		for k in range(i + 1, n):
			hcf = gcd(a[i], a[k])
			if hcf > mx:
				mx = hcf
				tp = a[k]
		a = remove(tp, i, a)
		ans.append(tp)
		a.insert(i + 1, mx)
		i += 1
	print(*ans)


def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	v = []
	for i in range(n):
		v.append(0)
	m = max(l)
	i = l.index(m)
	v[i] = 1
	print(m, end=' ')
	g = m
	for j in range(n - 1):
		t = 1
		for i in range(n):
			if v[i] == 0:
				temp = gcd(g, l[i])
				if temp >= t:
					k = i
					t = temp
		g = t
		v[k] = 1
		print(l[k], end=' ')
	print()


t = int(input())
i = 0
while i < t:
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	krat = []
	MAX = max(a)
	z = MAX
	while z > 0:
		if MAX % z == 0:
			krat.append(z)
		z -= 1
	indexK = 0
	while indexK < len(krat):
		K = krat[indexK]
		index = 0
		while index < n and krat[indexK] != -1:
			if a[index] % K == 0 and a[index] != 0:
				b.append(a[index])
				indK = indexK
				while indK < len(krat):
					if a[index] % krat[indK] != 0:
						del krat[indK]
						krat.insert(indK, -1)
					indK += 1
				del a[index]
				a.insert(index, 0)
			index += 1
		indexK += 1
	B = ''
	for j in b:
		B += str(j) + ' '
	print(B)
	i += 1


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = sorted(list(map(int, input().split())), reverse=True)
	di = {}
	for i in a:
		di[i] = 1 if i not in di else di[i] + 1
	b = [0] * n
	b[0] = a[0]
	g = b[0]
	di[g] -= 1
	if di[g] == 0:
		di.pop(g)
	f = [0] * 2000
	for i in range(1, n):
		gm = 0
		for x in di:
			f[gcd(x, g)] = x
			gm = max(gm, gcd(x, g))
		b[i] = f[gm]
		di[f[gm]] -= 1
		if di[f[gm]] == 0:
			di.pop(f[gm])
		g = gm
	print(*b)


for _ in range(int(input())):
	from math import gcd
	n = int(input())
	l = list(map(int, input().split()))
	m = max(l)
	lm = m
	seen = (m + 1) * [0]
	ans = []
	while len(ans) < n:
		a = []
		for i in range(n):
			if seen[l[i]] == 0 and gcd(lm, l[i]) > m:
				a.clear()
				a.append(l[i])
				m = gcd(lm, l[i])
			elif seen[l[i]] == 0 and gcd(lm, l[i]) == m:
				a.append(l[i])
		ans += a
		for i in a:
			seen[i] = 1
		lm = m
		m = 0
	print(' '.join(list(map(str, ans))))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = [0 for i in range(n)]
	m1 = max(l)
	r = [m1]
	d[l.index(m1)] = 1
	p = m1
	for i in range(n - 1):
		m = 0
		x = 0
		for j in range(n):
			g = gcd(p, l[j])
			if m == 0 and d[j] != 1 and (g > m):
				m = g
				x = j
			elif m > 0 and d[j] != 1 and (g > m):
				m = g
				x = j
			elif m > 0 and d[j] != 1 and (g == m):
				if l[j] > l[x]:
					m = g
					x = j
		r.append(l[x])
		d[x] = 1
		p = gcd(l[x], p)
	print(*r)


from math import gcd
for q in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())), reverse=True)
	ind = -1
	g = a[0]
	j = 1
	while j < n:
		tmp = 0
		for i in range(j, n):
			y = gcd(g, a[i])
			if y > tmp:
				tmp = y
				ind = i
		(a[j], a[ind]) = (a[ind], a[j])
		g = tmp
		j += 1
	print(*a)


def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
t = int(input())
while t > 0:
	t = t - 1
	n = int(input())
	a = [int(j) for j in input().split()]
	maxgcd = max(a)
	b = [max(a)]
	a.remove(max(a))
	n = n - 1
	while n > 0:
		tempgcd = 0
		tempele = 0
		for i in range(len(a)):
			currgcd = gcd(maxgcd, a[i])
			if currgcd >= tempgcd:
				tempgcd = currgcd
				tempele = a[i]
		b.append(tempele)
		a.remove(tempele)
		maxgcd = tempgcd
		n = n - 1
	for i in b:
		print(i, end=' ')
	print()


import sys
input = sys.stdin.readline

def gcd(a, b):
	return b if a % b == 0 else gcd(b, a % b)
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = [a[-1]]
	g = a.pop()
	while a:
		b = 0
		bi = 0
		for i in range(len(a)):
			if gcd(g, a[i]) >= b:
				b = gcd(g, a[i])
				bi = i
		g = b
		ans.append(a.pop(bi))
	print(*ans)


import math
t = int(input())
for c in range(t):
	n = int(input())
	arr = [int(x) for x in input().split(' ')]
	result = []
	cur_gcd = max(arr)
	while len(arr) > 0:
		max_index = 0
		max_gcd = 1
		for i in range(len(arr)):
			new_gcd = math.gcd(cur_gcd, arr[i])
			if new_gcd >= max_gcd:
				max_gcd = new_gcd
				max_index = i
		cur_gcd = max_gcd
		result.append(arr.pop(max_index))
	for i in result:
		print(i, end=' ')
	print()


def gcd(a: int, b: int) -> int:
	return a if b == 0 else gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	i = 0
	cm = a[0]
	while i < n - 1:
		j = i + 1
		m = i + 1
		cm = gcd(cm, a[i])
		gm = 1
		while j < n:
			g = gcd(cm, a[j])
			if g > gm:
				gm = g
				m = j
			j += 1
		if m != i + 1:
			(a[i + 1], a[m]) = (a[m], a[i + 1])
		i += 1
	print(*a)


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
from collections import Counter
for __ in range(itg()):
	n = itg()
	arr = list(mpint())
	arr.sort()
	gg = arr.pop()
	ans = [gg]
	counter = Counter(arr)
	while counter:
		(best_key, best_value) = (None, 0)
		for key in counter.keys():
			g = gcd(key, gg)
			if g > best_value:
				(best_key, best_value) = (key, g)
			elif g == best_value:
				best_key = max(best_key, key)
		ans.append(best_key)
		gg = gcd(gg, best_key)
		counter[best_key] -= 1
		if counter[best_key] == 0:
			del counter[best_key]
	print(*ans)


def GCD(a, b):
	return GCD(b, a % b) if a % b else b

def swap(lst, i, j):
	(lst[i], lst[j]) = (lst[j], lst[i])
for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	swap(a, 0, a.index(max(a)))
	gcd = a[0]
	for i in range(1, n):
		b = [0 for _ in range(i)]
		for j in range(i, n):
			b.append(GCD(gcd, a[j]))
		gcd = max(b)
		swap(a, i, b.index(gcd))
	print(' '.join(map(str, a)))


import math
import re
import itertools
import copy
import time
import sys
import functools

def input_linear(lamb=lambda x: int(x), seperator=' '):
	return map(lamb, input().split(seperator))

def input_array(lamb=lambda x: int(x), seperator=' '):
	return list(map(lamb, input().split(seperator)))

def input_matrix(rows, lamb=lambda x: int(x), seperator=' '):
	tmp_matrix = []
	for i in range(rows):
		tmp_matrix.append(input_array(lamb, seperator))
	return tmp_matrix

def input_graph_al_pair(vertices, lines, lamb=lambda x: int(x), seperator=' ', directional=False, remove_dup=False):
	temp_matrix = [x[:] for x in [[]] * vertices]
	if not directional:
		if not remove_dup:
			for i in range(lines):
				(ina, inb) = input_linear(lamb, seperator)
				temp_matrix[ina].append(inb)
				temp_matrix[inb].append(ina)
		else:
			for i in range(lines):
				(ina, inb) = input_linear(lamb, seperator)
				if inb not in temp_matrix[ina]:
					temp_matrix[ina].append(inb)
				if ina not in temp_matrix[inb]:
					temp_matrix[inb].append(ina)
		return temp_matrix
	else:
		if not remove_dup:
			for i in range(lines):
				(ina, inb) = input_linear(lamb, seperator)
				temp_matrix[ina].append(inb)
		else:
			for i in range(lines):
				(ina, inb) = input_linear(lamb, seperator)
				if inb not in temp_matrix[ina]:
					temp_matrix[ina].append(inb)
		return temp_matrix
for _ in range(int(input())):
	n = int(input())
	a = input_array()
	last = max(a)
	for i in range(n):
		if i != 0:
			print('', end=' ')
		curr = max(a, key=lambda x: math.gcd(x, last))
		print(curr, end='')
		a.remove(curr)
		last = math.gcd(curr, last)
	print('')


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	for _ in range(ri()):
		n = ri()
		a = ria()
		b = [0] * n
		mcurr = -1
		for i in range(n):
			if a[i] > mcurr:
				mcurr = a[i]
				ita = i
		ans = [mcurr]
		b[ita] = 1
		g = mcurr
		for i in range(1, n):
			mcurr = -1
			gnew = 0
			for j in range(n):
				if b[j] == 0:
					if math.gcd(a[j], g) > gnew:
						gnew = math.gcd(a[j], g)
						mcurr = a[j]
						ita = j
			g = gnew
			ans.append(mcurr)
			b[ita] = 1
		print(*ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	di = {}
	for i in a:
		di[i] = di.get(i, 0) + 1
	ans = [a[0]] * di[a[0]]
	val = a[0]
	while di[val]:
		a.remove(val)
		di[val] -= 1
	g = 1
	temp = val
	for i in a:
		if gcd(val, i) > g:
			temp = i
			g = gcd(val, i)
	val = temp
	ans += [val] * di[val]
	while di[val]:
		a.remove(val)
		di[val] -= 1
	if val == -1 or g == 1:
		print(*ans + a)
	else:
		val = g
		g = 1
		while a:
			temp = val
			for i in a:
				if gcd(val, i) > g:
					temp = i
					g = gcd(val, i)
			val = temp
			if g == 1:
				break
			ans += [val] * di[val]
			while di[val]:
				a.remove(val)
				di[val] -= 1
			val = g
			g = 1
		ans += a
		print(*ans)


import sys
sys.setrecursionlimit(10 ** 8)
try:
	FILE_POINTER = open('input.inpt')
	input = FILE_POINTER.readline
except:
	FILE_POINTER = None
	input = sys.stdin.readline

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	arr.sort(key=lambda x: -x)
	ans = [arr[0]]
	gcdtill = arr[0]
	arr[0] = -1
	for i in range(n - 1):
		mx = 0
		nxt = 0
		for j in range(n):
			if arr[j] != -1:
				gcdj = gcd(gcdtill, arr[j])
				if gcdj > mx:
					mx = gcdj
					nxt = j
		ans.append(arr[nxt])
		arr[nxt] = -1
		gcdtill = mx
	for i in ans:
		print(i, end=' ')
	print()
if FILE_POINTER:
	FILE_POINTER.close()


import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	mgcd = max(l)
	l.remove(max(l))
	k = []
	k.append(mgcd)
	while len(l) > 0:
		ans = 0
		ind = 0
		for i in range(len(l)):
			kk = math.gcd(mgcd, l[i])
			if kk > ans:
				ans = kk
				ind = i
		k.append(l[ind])
		mgcd = math.gcd(mgcd, ans)
		l.remove(l[ind])
	print(*k)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a
for _ in range(II()):
	n = II()
	aa = LI()
	mx = max(aa)
	i = aa.index(mx)
	ans = [mx]
	aa[i] = -1
	while len(ans) < n:
		now = mx
		mx = -1
		mxi = []
		for (i, a) in enumerate(aa):
			if a == -1:
				continue
			g = gcd(now, a)
			if g == mx:
				mxi.append(i)
			elif g > mx:
				mx = g
				mxi = [i]
		for i in mxi:
			ans.append(aa[i])
			aa[i] = -1
	print(*ans)


import math, queue, heapq
import sys
sys.setrecursionlimit(10 ** 6)
fastinput = sys.stdin.readline
fastout = sys.stdout.write
t = int(fastinput())
while t:
	t -= 1
	n = int(fastinput())
	a = list(map(int, fastinput().split()))
	a.sort()
	ans = []
	ans.append(a.pop())
	mem = [True] * (n - 1)
	lasttgcd = ans[-1]
	for i in range(n - 1):
		temp = -1
		mnn = 0
		for j in range(n - 1):
			if mem[j] == True:
				y = math.gcd(lasttgcd, a[j])
				if y > mnn:
					mnn = y
					temp = j
		if temp != -1:
			mem[temp] = False
			ans.append(a[temp])
			lasttgcd = math.gcd(lasttgcd, ans[-1])
	print(*ans)


from math import gcd
from collections import Counter

def upd(val, coua, bp, rem):
	(p, q) = (-1, None)
	for ele in coua:
		r = gcd(val, ele)
		if r > p:
			q = ele
			p = r
	bp += [q for x in range(coua[q])]
	rem -= coua[q]
	val = p
	del coua[q]
	return (val, coua, bp, rem)
for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	ma = max(a)
	cma = sum((x == ma for x in a))
	bp = [ma for x in range(cma)]
	coua = Counter(a)
	del coua[ma]
	val = ma
	rem = n - cma
	while val != 1 and rem != 0:
		(val, coua, bp, rem) = upd(val, coua, bp, rem)
	if rem:
		bp += [x for x in coua.elements()]
	print(*bp)


from math import gcd

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		A = [int(x) for x in input().split()]
		B = []
		x = max(A)
		B.append(x)
		A.remove(x)
		gcd_max = x
		n -= 1
		while n > 1:
			if gcd_max == 1:
				break
			else:
				gcd_old = 1
				for ele in A:
					gcd_curr = gcd(gcd_max, ele)
					if gcd_curr >= gcd_old:
						gcd_old = gcd_curr
						x = ele
				gcd_max = gcd_old
				B.append(x)
				A.remove(x)
			n -= 1
		for ele in A:
			B.append(ele)
		print(*B, sep=' ')
main()


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(ans, used) = ([], [])
	for i in range(n):
		used.append(False)
	cur = 0
	for i in range(n):
		(mx, idx) = (0, -1)
		for j in range(n):
			if math.gcd(cur, a[j]) >= mx and used[j] == False:
				mx = math.gcd(cur, a[j])
				idx = j
		ans.append(a[idx])
		used[idx] = True
		cur = mx
	for x in ans:
		print(x, end=' ')
	print()


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	x = max(arr)
	b = [x]
	arr.remove(x)
	for i in range(n - 1):
		temp = -1
		k = 0
		m = 0
		for j in range(n - 1):
			if arr[j] != -1:
				if gcd(x, arr[j]) > temp:
					k = j
					m = arr[j]
					temp = gcd(x, arr[j])
		b.append(m)
		arr[k] = -1
		x = temp
	b = list(map(str, b))
	s = ' '.join(b)
	print(s)


import math
import sys
input = sys.stdin.buffer.readline

def solution():
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	ans = [0] * n
	ans[0] = l[0]
	flag = [0] * (n + 1)
	flag[0] = 1
	prev = l[0]
	for i in range(1, n):
		x = 0
		for j in range(n):
			if flag[j] == 1:
				continue
			g = math.gcd(prev, l[j])
			if g > x:
				x = g
				ele = j
		ans[i] = l[ele]
		prev = x
		flag[ele] = 1
	print(*ans)
t = int(input())
for _ in range(t):
	solution()


from fractions import Fraction
from collections import defaultdict
import math
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	n = int(input())
	l = list([int(x) for x in input().split()])
	l.sort(reverse=True)
	ans = [l[0]]
	vis = [0] * n
	vis[0] = 1
	gcdsf = l[0]
	for i in range(1, n):
		mg = 0
		p = 0
		for j in range(n):
			if vis[j]:
				continue
			if mg < math.gcd(l[j], gcdsf):
				mg = math.gcd(l[j], gcdsf)
				p = j
		if mg == 0:
			break
		gcdsf = mg
		vis[p] = 1
		ans.append(l[p])
	for i in range(n):
		if vis[i] == 0:
			ans.append(l[i])
	print(*ans)


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	for _ in range(int(input())):
		n = int(input())
		a = sorted(list(map(int, input().split())), reverse=True)
		f = [0] * n
		ans = [0] * n
		ans[0] = a[0]
		f[0] = 1
		prev = a[0]
		k = 1
		for k in range(1, n):
			(mx, pos) = max(((gcd(prev, ai), i) for (i, ai) in enumerate(a) if f[i] == 0))
			f[pos] = 1
			ans[k] = a[pos]
			prev = gcd(prev, a[pos])
		print(' '.join(map(str, ans)))
main()


import sys
from math import gcd

def solve(a):
	n = len(a)

	def largest_in_row(a, ignore_cols):
		mx = (-1, -1)
		for (i, v) in enumerate(a):
			if i in ignore_cols:
				continue
			if v > mx[0]:
				mx = (v, i)
		return mx
	b = [0] * n
	(maxval, ind) = largest_in_row(a, {})
	b[0] = a[ind]
	(last_ind, cum_gcd) = (ind, maxval)
	ignore_cols = {ind: True}
	for i in range(1, n):
		gcd_row = [gcd(cum_gcd, val) for val in a]
		(maxgcd, ind) = largest_in_row(gcd_row, ignore_cols)
		b[i] = a[ind]
		ignore_cols[ind] = True
		(last_ind, cum_gcd) = (ind, gcd(cum_gcd, maxgcd))
	return b
IN = [x.strip() for x in sys.stdin.readlines()]
T = int(IN[0])
cur = 1
for ti in range(T):
	n = int(IN[cur])
	a = [int(x) for x in IN[cur + 1].split(' ')]
	res = solve(a)
	print(' '.join([str(x) for x in res]))
	cur += 2


import sys

def gcd(a, b):
	return gcd(b, a % b) if a % b else b
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(sys.stdin.readline())
	list_num = list(map(int, sys.stdin.readline().split()))
	res = [0] * n
	(nm, ni) = (0, 0)
	for i in range(n):
		if list_num[i] > nm:
			nm = list_num[i]
			ni = i
	list_num[ni] = -1
	res[0] = nm
	for i in range(1, n):
		nn = 0
		for j in range(n):
			if list_num[j] == -1:
				continue
			v = gcd(nm, list_num[j])
			if v > nn:
				nn = v
				ni = j
		res[i] = list_num[ni]
		list_num[ni] = -1
		nm = nn
	print(*res)


import itertools
import math
import sys
from collections import defaultdict

def stdinWrapper():
	data = '7\n2\n2 5\n4\n1 8 2 3\n3\n3 8 9\n5\n64 25 75 100 50\n1\n42\n6\n96 128 88 80 52 7\n5\n2 4 8 16 17\n'
	for line in data.split('\n'):
		yield line
if '--debug' not in sys.argv:

	def stdinWrapper():
		while True:
			yield input()
inputs = stdinWrapper()

def inputWrapper():
	return next(inputs)

def getType(_type):
	return _type(inputWrapper())

def getArray(_type):
	return [_type(x) for x in inputWrapper().split()]

def solve(a):
	res = []
	_max = max(a)
	for i in range(len(a)):
		if a[i] == _max:
			res.append(a.pop(i))
			break
	_current_gcd = res[0]
	while a and _current_gcd > 1:
		_max_gcd = 0
		_i = -1
		for i in range(len(a)):
			_cur = math.gcd(_current_gcd, a[i])
			if _cur > _max_gcd:
				_max_gcd = _cur
				_i = i
		res.append(a.pop(_i))
		_current_gcd = _max_gcd
	res += a
	return res
t = getType(int)
for _ in range(t):
	n = getType(int)
	a = getArray(int)
	arr = solve(a)
	print(' '.join(list(map(str, arr))))


import math

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def solve():
	N = getInt()
	A = getInts()
	A.sort()
	ans = []
	ans.append(A.pop())
	curr_gcd = ans[0]
	while A:
		best = 0
		ind = -1
		for j in range(len(A)):
			x = math.gcd(A[j], curr_gcd)
			if x > best:
				best = x
				ind = j
		ans.append(A.pop(ind))
		curr_gcd = best
	print(*ans)
T = getInt()
for t in range(T):
	solve()


testcases = int(input())

def computeGCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for testcase in range(testcases):
	n = int(input())
	temparr = input()
	temparr = temparr.split()
	arr = []
	for i in temparr:
		arr.append(int(i))
	ans = []
	tempgcd = []
	ans.append(max(arr))
	tempgcd.append(max(arr))
	x = ans[-1]
	arr.pop(arr.index(max(ans)))
	arr1 = arr
	nlen = len(arr1)
	while nlen:
		curelem = tempgcd[-1]
		curbest = 0
		ans1 = 0
		for i in range(nlen):
			curb = computeGCD(curelem, arr1[i])
			if curb >= curbest:
				ans1 = arr1[i]
				curbest = curb
		ans.append(ans1)
		tempgcd.append(curbest)
		flag = 0
		arr2 = []
		for i in arr1:
			if i == ans1 and flag == 0:
				flag = 1
			else:
				arr2.append(i)
		arr1 = arr2[:]
		nlen -= 1
	ansstr = []
	for i in ans:
		ansstr.append(str(i))
	print(' '.join(ansstr))


from math import gcd

def solve():
	n = int(input())
	li = list(map(int, input().split()))
	li.sort(reverse=True)
	b = li[0:1]
	g = li[0]
	li = li[1:]
	while len(li):
		k = max(li, key=lambda x: gcd(x, g))
		g = gcd(k, g)
		li.remove(k)
		b.append(k)
	print(*b)
t = int(input())
for _ in range(t):
	solve()


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	aWork = []
	b = []
	for elem in a:
		aWork.append([1, elem, elem])
	for i in range(n):
		curElem = max(aWork)
		b.append(curElem[2])
		curElem[0] = 0
		for i in range(n):
			if aWork[i][0] == 1:
				aWork[i][1] = gcd(aWork[i][1], curElem[1])
	print(' '.join(map(str, b)))


def noda(a, b):
	while a * b != 0:
		if a > b:
			a = a % b
		else:
			b = b % a
	return a + b
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.reverse()
	b = [0] * n
	b[0] = a[0]
	a[0] = 0
	dm = b[0]
	for j in range(1, n):
		y = 0
		for i in range(n):
			if a[i] != 0:
				x = noda(dm, a[i])
				if x > y:
					y = x
					p1 = a[i]
					p2 = i
		a[p2] = 0
		b[j] = p1
		dm = y
	print(*b)


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	m = a.pop()
	a.reverse()
	ans = [m]
	for i in range(n - 1):
		mg = 1
		for j in range(len(a)):
			g = math.gcd(m, a[j])
			mg = max(g, mg)
			if mg == g:
				index = j
		m = mg
		ans.append(a[index])
		a.pop(index)
	print(*ans)


import math
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(*a)
	elif n == 2:
		a.sort(reverse=True)
		print(*a)
	else:
		maxi = max(a)
		res = [maxi]
		del a[a.index(maxi)]
		last = maxi
		second = 0
		n -= 1
		nex = 0
		while n:
			for i in range(n):
				b = math.gcd(last, a[i])
				if b >= second:
					second = b
					nex = a[i]
			res.append(nex)
			del a[a.index(nex)]
			last = second
			second = 0
			n -= 1
		print(*res)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	ans = [arr[0]]
	visited = [False] * n
	visited[0] = True
	p = arr[0]
	while len(ans) < n:
		(temp, tempPos) = (0, -1)
		for i in range(n):
			if not visited[i] and gcd(p, arr[i]) > temp:
				temp = gcd(p, arr[i])
				tempPos = i
		visited[tempPos] = True
		ans.append(arr[tempPos])
		p = gcd(p, arr[tempPos])
	print(' '.join(map(str, ans)))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	c = [0 for i in range(n)]
	b = [0 for i in range(n)]
	c[0] = max(arr)
	b[0] = max(arr)
	arr[arr.index(max(arr))] = -1
	for i in range(n - 1):
		ind = 0
		m = -1
		for j in range(len(arr)):
			if arr[j] != -1:
				g = gcd(arr[j], c[i])
				if g > m:
					c[i + 1] = g
					b[i + 1] = arr[j]
					ind = j
					m = g
		arr[ind] = -1
	print(*b)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def integer():
	return int(inp())

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def solve():
	n = integer()
	ar = lis()
	ar.sort(reverse=True)
	b = [ar[0]]
	c_g = ar[0]
	n_c = set(range(n))
	n_c.remove(0)
	while n_c:
		m = -9999999999999999999999999999999999999999999999
		c_i = -1
		for i in n_c:
			if gcd(c_g, ar[i]) > m:
				m = gcd(c_g, ar[i])
				c_i = i
		n_c.remove(c_i)
		b.append(ar[c_i])
		c_g = m
	print(*b)
testcase(integer())


import math
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	lst.sort(reverse=True)
	ans = [lst[0]]
	num = lst[0]
	lst.pop(0)
	for i in range(n - 1):
		m = len(lst)
		number = -1
		temp = -1
		for j in range(m):
			if math.gcd(num, lst[j]) > temp:
				temp = math.gcd(num, lst[j])
				number = j
		ans.append(lst[number])
		lst.pop(number)
		num = temp
	print(*ans)


from math import gcd
import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split() if i != '\n']
	maxa = max(a)
	ans = []
	ind = [0] * n
	for i in range(n):
		(tmp, store) = (0, 0)
		for j in range(n):
			if ind[j] == 0:
				gcd_ = gcd(maxa, a[j])
				if gcd_ > store:
					store = gcd_
					tmp = j
		ind[tmp] = 1
		maxa = store
		ans.append(a[tmp])
	ans = ' '.join(map(str, ans))
	sys.stdout.write(ans + '\n')


def mii():
	return map(int, input().split())

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for _ in range(int(input())):
	n = int(input())
	a = list(mii())
	ma = -10000000000.0
	mi = -1
	for i in range(n):
		if a[i] > ma:
			ma = a[i]
			mi = i
	picked = [0] * n
	print(ma, end=' ')
	picked[mi] = 1
	for i in range(n - 1):
		mag = -1
		magi = -1
		for j in range(n):
			if picked[j]:
				continue
			g = gcd(ma, a[j])
			if g > mag:
				mag = g
				magi = j
		print(a[magi], end=' ')
		picked[magi] = 1
		ma = mag
	print()


def gcd(x, y):
	while y > 0:
		(x, y) = (y, x % y)
	return x
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	biggest_value = 0
	for i in a:
		if i > biggest_value:
			biggest_value = i
	a.remove(biggest_value)
	b.append(biggest_value)
	current_gcd = biggest_value
	for _ in range(n - 1):
		biggest_gcd = 0
		number_for_biggest_gcd = 0
		for j in a:
			if gcd(current_gcd, j) > biggest_gcd:
				biggest_gcd = gcd(current_gcd, j)
				number_for_biggest_gcd = j
		a.remove(number_for_biggest_gcd)
		b.append(number_for_biggest_gcd)
		current_gcd = biggest_gcd
	print(*b)


import sys
pin = sys.stdin.readline

def GCD(a, b):
	(a, b) = (max(a, b), min(a, b))
	while b:
		(a, b) = (b, a % b)
	return a
for T in range(int(pin())):
	N = int(pin())
	A = [*map(int, pin().split())]
	A = sorted(A)[::-1]
	gcd = A[0]
	for n in range(N):
		mx = (1, 0)
		for (i, v) in enumerate(A):
			mx = max(mx, (GCD(gcd, v), i))
		print(A.pop(mx[1]), end=' ')
		gcd = mx[0]
	print()


from collections import defaultdict
import math
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	dic = defaultdict(lambda : 0)
	for i in range(n):
		dic[l[i]] += 1
	ans = [max(l)]
	GCD = max(l)
	dic[max(l)] -= 1
	prev_gcd = GCD
	for i in range(n - 1):
		max_gcd = 1
		m_i = n - 1
		for j in range(n):
			if dic[l[j]]:
				if math.gcd(prev_gcd, l[j]) >= max_gcd:
					max_gcd = math.gcd(prev_gcd, l[j])
					m_i = j
		dic[l[m_i]] -= 1
		ans.append(l[m_i])
		prev_gcd = math.gcd(prev_gcd, ans[-1])
	print(*ans)


from math import gcd
from sys import stdin, gettrace
from collections import Counter
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	n = int(inputi())
	aa = [int(a) for a in inputi().split()]
	aac = Counter(aa)
	i = max(range(n), key=lambda i: aa[i])
	bb = [aa[i]]
	g = aa[i]
	aa[i] = 0
	while True:
		bg = g
		try:
			i = max((j for j in range(n) if aa[j] != 0), key=lambda i: gcd(aa[i], g))
		except:
			break
		g = gcd(g, aa[i])
		bb.append(aa[i])
		aa[i] = 0
	print(' '.join(map(str, bb)))

def main():
	t = int(inputi())
	for _ in range(t):
		solve()
main()


import math
test_case = int(input())
for i in range(test_case):
	n = int(input())
	s = input().split(' ')
	L = [0] * n
	for j in range(n):
		L[j] = int(s[j])
	L.sort()
	L.reverse()
	LL = []
	gcd = L[0]
	LL.append(L[0])
	del L[0]
	while len(L) > 1:
		max_gcd = 1
		max_gcd_item = 0
		for j in range(len(L)):
			if math.gcd(gcd, L[j]) > max_gcd:
				max_gcd = math.gcd(gcd, L[j])
				max_gcd_item = L[j]
		if max_gcd == 1:
			break
		LL.append(max_gcd_item)
		gcd = max_gcd
		L.remove(max_gcd_item)
	s = ''
	for j in LL:
		s += str(j)
		s += ' '
	for j in L:
		s += str(j)
		s += ' '
	print(s[:-1])


import math
for t in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))[::-1]
	i = 1
	temp = a[0]
	add = -1
	while i < n:
		maxi = 0
		for j in range(i, n):
			if math.gcd(temp, a[j]) > maxi:
				maxi = math.gcd(temp, a[j])
				add = j
		(a[i], a[add]) = (a[add], a[i])
		temp = maxi
		i += 1
	print(*a)


import os
import sys
from io import BytesIO, IOBase
from math import gcd

def solution(arr, n):
	res = []
	srr = arr[:]
	mx = max(srr)
	srr.remove(mx)
	res.append(mx)
	c = [mx]
	while srr:
		cur = c[-1]
		rem = -1
		for x in srr:
			gc = gcd(x, cur)
			if gc > rem:
				rem = gc
				ele = x
		c.append(rem)
		res.append(ele)
		srr.remove(ele)
	write(*res)

def main():
	for _ in range(r_int()):
		n = r_int()
		arr = r_array()
		solution(arr, n)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def write(*args, end='\n'):
	for x in args[:-1]:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(str(args[-1]))
	sys.stdout.write(end)

def r_array():
	return [int(x) for x in input().split()]

def r_int():
	return int(input())
main()


from math import gcd
from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input().split()]
	dp = defaultdict(int)
	for a in arr:
		dp[a] += 1
	gc = max(arr)
	b = [gc]
	dp[gc] -= 1
	if dp[gc] == 0:
		del dp[gc]
	while dp:
		mgc = -1
		nex = None
		for key in list(dp.keys()):
			tgc = gcd(gc, key)
			if tgc > mgc:
				mgc = tgc
				nex = key
		gc = mgc
		dp[nex] -= 1
		b.append(nex)
		if dp[nex] == 0:
			del dp[nex]
	print(*b)


import math
t = int(input(''))
arr = []
for i in range(t):
	n = int(input(''))
	arr.append(list(map(int, input().split())))
for i in range(t):
	a = arr[i]
	n = len(a)
	a.sort(reverse=True)
	dp = []
	dp.append(a[0])
	c = []
	c.append(a[0])
	a[0] = 0
	for k in range(1, n):
		sol = 0
		for j in range(n):
			if a[j] == 0:
				continue
			d = math.gcd(c[k - 1], a[j])
			if d >= sol:
				sol = d
				pos = j
		dp.append(a[pos])
		c.append(math.gcd(c[k - 1], dp[k]))
		a[pos] = 0
		if sol == 1:
			break
	for j in range(n):
		if a[j] != 0:
			dp.append(a[j])
	print(*dp)


t = int(input())

def gcd(a: int, b: int):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def getseq(n: int, arr: list):
	seq_b = []
	curr_gcd = 0
	maximum_gcd = curr_gcd
	max_index = 0
	visited = [False for i in range(n)]
	for i in range(n):
		max_index = 0
		maximum_gcd = 0
		for j in range(n):
			if not visited[j] and gcd(arr[j], curr_gcd) > maximum_gcd:
				maximum_gcd = gcd(arr[j], curr_gcd)
				max_index = j
		curr_gcd = maximum_gcd
		visited[max_index] = True
		seq_b.append(arr[max_index])
	for i in seq_b:
		print(i, end=' ')
for _ in range(t):
	n = int(input())
	seq = list(map(int, input().split(' ')))
	getseq(n, seq)
	print('')


import math
TC = int(input())
for _ in range(TC):
	n = int(input())
	a = list(map(int, input().split()))
	mark = [False] * n
	prev = 0
	for i in range(n):
		idx = 0
		cur = 0
		for j in range(n):
			if mark[j] == True:
				continue
			if math.gcd(prev, a[j]) > cur:
				cur = math.gcd(prev, a[j])
				idx = j
		mark[idx] = True
		prev = cur
		print(a[idx], end=' ')
	print()


import math

def solve(n, arr):
	b = [max(arr)]
	arr.remove(max(arr))
	currGCD = b[0]
	while arr:
		factors = [math.gcd(x, currGCD) for x in arr]
		currGCD = max(factors)
		next_b = arr[factors.index(currGCD)]
		b.append(next_b)
		arr.remove(next_b)
	return b

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = [int(x) for x in input().split()]
		assert n == len(arr)
		answer = ' '.join([str(x) for x in solve(n, arr)])
		print(answer)
main()


import math

def solution():
	n = int(input())
	l = list(map(int, input().split()))
	g = max(l)
	pg = l.index(g)
	gcd = 1
	l = l[:pg] + l[pg + 1:]
	print(g, end=' ')
	while len(l) > 0:
		for i in range(len(l)):
			cgcd = math.gcd(g, l[i])
			if cgcd > gcd:
				gcd = cgcd
				pg = i
		if gcd == 1:
			break
		print(l[pg], end=' ')
		g = gcd
		gcd = 1
		l = l[:pg] + l[pg + 1:]
	for i in range(len(l)):
		print(l[i], end=' ')
	print('')
t = int(input())
while t > 0:
	solution()
	t -= 1


import math

def crypto(n, a):
	first = max(a)
	ans = [first]
	old = first
	a.remove(first)
	while a:
		gcds = [math.gcd(x, old) for x in a]
		ind = gcds.index(max(gcds))
		ans.append(a[ind])
		old = gcds[ind]
		del a[ind]
	return ans
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(*crypto(n, a))


import math
test_cases = int(input())
for test_case in range(test_cases):
	n = int(input())
	a = list(map(int, input().split()))
	gcd = 0
	a.sort(reverse=True)
	ans = [a[0]]
	a.pop(0)
	x = 1
	i = ans[-1]
	while True:
		max = 0
		for j in a:
			if math.gcd(i, j) >= max:
				max = math.gcd(i, j)
				x = j
		if len(a) == 0:
			break
		ans.append(x)
		a.remove(x)
		i = max
		if i == 1:
			ans.extend(a)
			break
	print(*ans)


from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math
import heapq

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		n = iin()
		a = ain()
		ans = deque([])
		v = [0] * n
		maxi = max(a)
		idx = a.index(maxi)
		ans.append(maxi)
		v[idx] = 1
		c = n - 1
		curr_gcd = maxi
		while c > 0:
			d = deque([])
			maxi = -1
			for i in range(n):
				if v[i] == 0:
					x = math.gcd(curr_gcd, a[i])
					if x > maxi:
						maxi = x
						d = deque([i])
					elif x == maxi:
						d.append(i)
			for j in d:
				c -= 1
				v[j] = 1
				ans.append(a[j])
			curr_gcd = maxi
		print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def gcd(a, b):
	a = abs(a)
	b = abs(b)
	while b != 0:
		(a, b) = (b, a % b)
	return a

def solve(a):
	b = []
	b.append(a.pop())
	g = b[len(b) - 1]
	for i in range(len(a)):
		k = -1
		m = 0
		for j in range(len(a) - 1, -1, -1):
			gc = gcd(g, a[j])
			if gc > m:
				m = gc
				k = j
		b.append(a[k])
		g = m
		a.pop(k)
	return b
N = int(input())
for i in range(N):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	print(*solve(a))


import sys
input = sys.stdin.readline
from bisect import bisect_left
from bisect import bisect_right
from math import ceil, factorial

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	n = int(input())
	a = sorted(int_array(), reverse=1)
	ans = [max(a)]
	a.remove(max(a))
	ggg = ans[0]
	while len(ans) != n:
		g = 1
		num = None
		for i in a:
			if gcd(i, ggg) >= g:
				g = gcd(i, ggg)
				num = i
		ans.append(num)
		a.remove(num)
		ggg = gcd(ggg, num)
	print(*ans)


from collections import *
import sys

def computeGCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))
t = ri()
for _ in range(t):
	n = ri()
	aa = rl()
	bb = []
	gcd = max(aa)
	bb.append(max(aa))
	aa.remove(max(aa))
	while aa:
		if gcd == 1:
			for ai in aa:
				bb.append(ai)
			break
		mini = 1
		for ai in aa:
			temp = computeGCD(gcd, ai)
			if temp >= mini:
				mini = temp
				curr = ai
		gcd = mini
		bb.append(curr)
		aa.remove(curr)
	print(*bb)


from math import gcd

def solve(n, a):
	imax = 0
	for i in range(1, n):
		if a[i] > a[imax]:
			imax = i
	notwas = [True] * n
	notwas[imax] = False
	prevgcd = a[imax]
	ans = [a[imax]]
	for i in range(n - 1):
		max1 = 0
		max_now = 0
		for j in range(n):
			if notwas[j]:
				if gcd(a[j], prevgcd) > max1:
					max_now = j
					max1 = gcd(a[max_now], prevgcd)
		ans.append(a[max_now])
		notwas[max_now] = False
		prevgcd = max1
	return ans
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(*solve(n, a))


import math
for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	s = []
	maxi = max(arr)
	s.append(maxi)
	arr.remove(maxi)
	g = maxi
	for ___ in range(len(arr)):
		toadd = 0
		diff = math.inf
		for ele in arr:
			if g - math.gcd(g, ele) < diff:
				diff = g - math.gcd(g, ele)
				toadd = ele
		s.append(toadd)
		arr.remove(toadd)
		diff = math.inf
		g = math.gcd(g, toadd)
	print(*s)


from collections import defaultdict
import math
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	freq = defaultdict(int)
	maxi = float('-inf')
	for x in a:
		freq[x] += 1
		maxi = max(maxi, x)
	ans = [maxi]
	i = 1
	freq[maxi] -= 1
	while i < n:
		curr_max = 0
		next = None
		for num in a:
			if freq[num]:
				if math.gcd(maxi, num) > curr_max:
					curr_max = math.gcd(maxi, num)
					next = num
		freq[next] -= 1
		ans.append(next)
		maxi = curr_max
		i += 1
	print(*ans)


from collections import Counter
import string
import math
import sys
from fractions import Fraction

def array_int():
	return [int(i) for i in sys.stdin.readline().split()]

def vary(arrber_of_variables):
	if arrber_of_variables == 1:
		return int(sys.stdin.readline())
	if arrber_of_variables >= 2:
		return map(int, sys.stdin.readline().split())

def makedict(var):
	return dict(Counter(var))

def printDivisors(n):
	divisors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				divisors.append(i)
			else:
				divisors.extend((i, n // i))
		i = i + 1
	return divisors

def countTotalBits(num):
	binary = bin(num)[2:]
	return len(binary)

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
for _ in range(vary(1)):
	n = vary(1)
	num = array_int()
	num.sort(reverse=True)
	seq = []
	seq.append(num[0])
	if n == 1:
		print(num[0])
		continue
	j = 0
	while j < n - 1:
		maxi = -1
		for i in range(j + 1, n):
			z = math.gcd(seq[-1], num[i])
			if z > maxi:
				maxi = z
				pos = i
		(num[j + 1], num[pos]) = (num[pos], num[j + 1])
		seq.append(maxi)
		j += 1
	print(*num)


from __future__ import division, print_function
import sys
import math
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(ai) for ai in input().split()]
	m = max(a)
	used = [0] * n
	sol = [0] * n
	cur = m
	for i in range(n):
		idx = -1
		best = 0
		for j in range(n):
			if not used[j]:
				g = math.gcd(cur, a[j])
				if best < g:
					best = g
					idx = j
		used[idx] = 1
		sol[i] = a[idx]
		cur = math.gcd(sol[i], cur)
	print(*sol)


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	sol = []
	boro_nb = max(l)
	while len(l) != 0:
		Max = 0
		for i in l:
			temp = gcd(boro_nb, i)
			if temp > Max:
				Max = temp
				element = i
		boro_nb = Max
		sol.append(element)
		l.remove(element)
	print(*sol)


def gcd(a, b):
	(a, b) = (max(a, b), min(a, b))
	while b > 0:
		(a, b) = (b, a % b)
	return a

def gcd_collection(a, item):
	val = a[0]
	for ai in a:
		val = min(val, gcd(ai, item))
	return val

def calc(a):
	a.sort()
	max_val = a[-1]
	a[-1] = 0
	res = [0 for i in range(len(a))]
	res[0] = max_val
	cg = max_val
	for i in range(1, len(a)):
		(ci, cans) = (0, 0)
		for j in range(len(a)):
			if a[j] and gcd(a[j], cg) > cans:
				cans = gcd(a[j], cg)
				ci = j
		res[i] = a[ci]
		cg = cans
		a[ci] = 0
	return res

def get_ints():
	return [int(n) for n in input().split()]

def get_floats():
	return [float(n) for n in input().split()]

def seq2str(seq):
	return ' '.join((str(item) for item in seq))
zzz = get_ints()
assert len(zzz) == 1
t = zzz[0]
for i in range(t):
	zzz = get_ints()
	assert len(zzz) == 1
	n = zzz[0]
	zzz = get_ints()
	assert len(zzz) == n
	a = zzz
	res = calc(a)
	print(seq2str(res))


t = int(input())
for i in range(t):
	n = int(input())
	flg = [0 for _ in range(n)]
	a = list(map(int, input().split()))
	b = [max(a)]
	check = []
	for s in range(1, b[0] + 1):
		if b[0] % s == 0:
			check.append(s)
	check.reverse()
	flg[a.index(b[0])] = 1
	count = 0
	flg_2 = 0
	while count <= len(check) - 1:
		for t in range(len(b)):
			if b[t] % check[count] != 0:
				flg_2 = 1
		for j in range(n):
			if a[j] % check[count] == 0 and flg[j] == 0 and (flg_2 == 0):
				b.append(a[j])
				flg[j] = 1
		count += 1
		flg_2 = 0
	for k in range(n):
		if flg[k] == 0:
			b.append(a[k])
	for l in range(n):
		print(b[l], end=' ')
	print()


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort(reverse=True)
	g = a[0]
	for i in range(1, n):

		def func(x):
			return gcd(g, x)
		a[i:n] = sorted(a[i:n], reverse=True, key=func)
		g = gcd(g, a[i])
	print(' '.join([str(x) for x in a]))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	lst = [int(i) for i in input().split()]
	b = list()
	b.append(max(lst))
	lst.remove(max(lst))
	num = b[0]
	for j in range(n - 1):
		g = 0
		for k in range(n - j - 1):
			a = gcd(num, lst[k])
			if a > g:
				(x, g) = (lst[k], a)
		num = g
		lst.remove(x)
		b.append(x)
		if x == 1:
			b += lst
			break
	print(*b)


def swap(arr, i, j):
	temp = arr[i]
	arr[i] = arr[j]
	arr[j] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = int(input())
for i in range(t):
	size = int(input())
	arr = [int(n) for n in input().split()]
	maxi = arr[0]
	idx = 0
	for j in range(1, size):
		if maxi < arr[j]:
			maxi = arr[j]
			idx = j
	swap(arr, idx, 0)
	old_gcd = arr[0]
	for j in range(size - 1):
		maxi = -1
		idx = -1
		for k in range(j + 1, size):
			div = gcd(old_gcd, arr[k])
			if maxi == -1 or maxi < div:
				maxi = div
				idx = k
		swap(arr, j + 1, idx)
		old_gcd = maxi
	print(' '.join(map(str, arr)))


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))

def prime_factors(n):
	factors = dict()
	for i in range(2, math.ceil(math.sqrt(n)) + 1):
		while n % i == 0:
			if i in factors:
				factors[i] += 1
			else:
				factors[i] = 1
			n = n // i
	if n > 2:
		factors[n] = 1
	return factors

def solve():
	n = get_int()
	ls = get_list()
	start = max(ls)
	ans = [start]
	st = [i for i in range(n)]
	st.remove(ls.index(start))
	n -= 1
	while n:
		till_max = 0
		new_ind = 0
		for i in st:
			gcd = math.gcd(start, ls[i])
			if gcd > till_max:
				till_max = gcd
				new_ind = i
		ans.append(ls[new_ind])
		start = till_max
		st.remove(new_ind)
		n -= 1
	print(*ans)

def main():
	solve()
TestCases = True
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


from sys import stdin
from math import gcd
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	used = [False] * n
	cur = 0
	b = []
	for j in range(n):
		best = 0
		for i in range(n):
			if used[i]:
				continue
			g = gcd(cur, a[i])
			if g > best:
				best = g
				best_idx = i
		used[best_idx] = True
		cur = best
		b.append(a[best_idx])
	print(*b)


from math import gcd
import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for i in range(T):
	(N,) = map(int, input().split())
	X = list(map(int, input().split()))
	ns = set(range(N))
	Y = []
	g = max(X)
	for i in range(N):
		mx = 0
		for j in ns:
			gg = gcd(X[j], g)
			if gg > mx:
				(t, mx) = (j, gg)
		g = mx
		Y.append(X[t])
		ns.remove(t)
	print(*Y)


from math import sqrt, gcd
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [max(a)] * n
	ind = a.index(max(a))
	ans = [a[ind]]
	a[ind] = -1
	prevgcd = ans[-1]
	for j in range(n - 1):
		ma = 0
		mi = 0
		for i in range(n):
			if a[i] != -1:
				cur = gcd(a[i], prevgcd)
				if cur < b[i]:
					b[i] = cur
				cur = b[i]
				if ma < cur:
					mi = i
					ma = cur
		ans.append(a[mi])
		prevgcd = gcd(prevgcd, a[mi])
		a[mi] = -1
	print(*ans)


def gcd(a, b):
	while a % b != 0:
		(a, b) = (b, a % b)
	return b

def bigGCD(a):
	maxGcd = max(a)
	b = []
	while maxGcd > 1:
		if maxGcd in a:
			b.append(maxGcd)
			a.remove(maxGcd)
		maxNow = 1
		best = 0
		for i in a:
			if gcd(maxGcd, i) > maxNow:
				maxNow = gcd(maxGcd, i)
				best = i
		if best != 0:
			b.append(best)
			a.remove(best)
		maxGcd = maxNow
	while a:
		b.append(a.pop(0))
	return b
cases = int(input())
for i in range(cases):
	n = int(input())
	a = list(map(int, input().strip().split()))
	ans = bigGCD(a)
	print(f"{' '.join(map(str, ans))}")


from math import gcd

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		l = [max(a)]
		a.remove(l[-1])
		s = l[-1]
		while a:
			m = -1
			ans = -1
			for j in range(len(a)):
				if gcd(a[j], s) > m:
					m = gcd(a[j], s)
					ans = a[j]
			s = m
			l.append(ans)
			a.remove(ans)
		print(*l)
main()


import math
t = int(input())
for i in range(t):
	n = int(input())
	lst = list(map(int, input().split()))
	lst.sort()
	lsta = [lst[-1]]
	lst.pop()
	g = lsta[0]
	while lst != []:
		ma = -1000000000.0
		val = -1000000000.0
		for d in lst:
			if math.gcd(g, d) > ma:
				ma = math.gcd(g, d)
				val = d
		g = ma
		lsta.append(val)
		lst.remove(val)
	print(*lsta)


import math
b = []

def solve(a, mx):
	if len(a) == 0:
		return
	for i in range(mx, 0, -1):
		if mx % i == 0:
			d = []
			for j in a:
				if j % i == 0:
					d.append(j)
			if len(d) > 0:
				for k in d:
					a.remove(k)
					b.append(k)
				solve(a, i)
				return
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	b = []
	mx = max(a)
	a.remove(mx)
	b.append(mx)
	solve(a, mx)
	print(*b)


import math

def solve(n, ar):
	ar = sorted(ar, reverse=True)
	curr_gcd = ar[0]
	for i in range(1, n):
		ptr = i
		maxi = 0
		maxi_ind = 0
		while ptr < n:
			if math.gcd(curr_gcd, ar[ptr]) >= maxi:
				maxi = math.gcd(curr_gcd, ar[ptr])
				maxi_ind = ptr
			ptr += 1
		curr_gcd = maxi
		(ar[i], ar[maxi_ind]) = (ar[maxi_ind], ar[i])
	print(' '.join(map(str, ar)))
t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	solve(n, ar)


from sys import stdin, stdout
input = stdin.readline
from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * n
	c = [0]
	d = []
	for i in range(n):
		l = c[-1]
		for j in range(n):
			if b[j] == 0:
				k = gcd(l, a[j])
				break
		for j in range(n):
			if b[j] == 0:
				k = max(k, gcd(l, a[j]))
		for j in range(n):
			if b[j] == 0:
				r = gcd(c[-1], a[j])
				if r == k:
					c.append(k)
					d.append(a[j])
					b[j] = 1
					break
	stdout.write(' '.join((str(i) for i in d)) + '\n')


import sys
input = sys.stdin.readline
from math import gcd

def f():
	n = int(input())
	A = list(map(int, input().split()))
	C = [0] * n
	now = 0
	L = []
	for _ in range(n):
		idx = -1
		temp = -1
		for (i, a) in enumerate(A):
			if not C[i]:
				g = gcd(a, now)
				if g > temp:
					temp = g
					idx = i
		C[idx] = 1
		now = temp
		L.append(A[idx])
	print(*L)
t = int(input())
for x in range(t):
	f()


from sys import stdin
from math import gcd
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	a = [int(x) for x in inp().split()]
	ans = [max(a)]
	used = set()
	used.add(a.index(ans[-1]))
	gcdC = ans[-1]
	for i in range(n - 1):
		maxGCD = -1
		maxInd = -1
		for j in range(n):
			if j not in used and gcd(gcdC, a[j]) > maxGCD:
				maxGCD = gcd(gcdC, a[j])
				maxInd = j
		gcdC = maxGCD
		used.add(maxInd)
		ans.append(a[maxInd])
	print(*ans)


from sys import stdin, stdout

class SOLVE:

	def GCD(self, a, b):
		if a == 0:
			return b
		return self.GCD(b % a, a)

	def solve(self):
		R = stdin.readline
		W = stdout.write
		ans = []
		for i in range(int(input())):
			n = int(R())
			a = [int(x) for x in R().split()]
			a.sort(reverse=True)
			ans += [str(a[0]) + ' ']
			gcd = a[0]
			a[0] = -1
			for j in range(n - 1):
				mx = pos = 0
				for k in range(n):
					if a[k] != -1:
						tmp = self.GCD(gcd, a[k])
						if tmp > mx:
							mx = tmp
							pos = k
				ans += [str(a[pos]) + ' ']
				a[pos] = -1
				gcd = mx
			ans += ['\n']
		W(''.join(ans))

def main():
	s = SOLVE()
	s.solve()
main()


TC = int(input())

def gcd(a, b):
	while b > 0:
		(a, b) = (b, a % b)
	return a
for tc in range(TC):
	N = int(input())
	A = list(map(int, input().split()))
	M = {}
	maxA = A[0]
	for a in A:
		M[a] = M.setdefault(a, 0) + 1
		maxA = max(maxA, a)
	result = []
	for _ in range(M.pop(maxA)):
		result.append(maxA)
	g = result[-1]
	while M:
		mx = 0
		vx = 0
		for i in M:
			t = gcd(g, i)
			if t > mx:
				mx = t
				vx = i
		g = mx
		for _ in range(M.pop(vx)):
			result.append(vx)
	for r in result:
		print(r, end=' ')
	print()


import sys, math
tc = int(sys.stdin.readline())
for _ in range(tc):
	n = int(sys.stdin.readline())
	arr = list(map(int, sys.stdin.readline().split()))
	check = [False] * n
	ans = [0] * n
	ans[0] = max(arr)
	check[arr.index(max(arr))] = True
	now = ans[0]
	for i in range(1, n):
		temp = []
		for j in range(n):
			if not check[j]:
				temp.append((math.gcd(now, arr[j]), j))
		temp.sort(key=lambda x: -x[0])
		ans[i] = arr[temp[0][1]]
		check[temp[0][1]] = True
		now = temp[0][0]
	print(' '.join(map(str, ans)))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = sorted(map(int, input().split()))
	gd = [l[-1]]
	l.remove(l[-1])
	mx = gd[-1]
	while len(l) > 0:
		(num, mx_gcd) = (0, 0)
		for i in l:
			temp = gcd(i, mx)
			if temp > mx_gcd:
				num = i
				mx_gcd = temp
		gd.append(num)
		l.remove(num)
		mx = gcd(mx, num)
	for i in range(n):
		print(gd[i], end=' ')
	print()


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	maxx = max(arr)
	arr.remove(maxx)
	c = [maxx]
	crnt_gcd = maxx
	while arr:
		(now_gcd, now_ind) = (0, 0)
		for i in range(len(arr)):
			now = gcd(crnt_gcd, arr[i])
			if now > now_gcd:
				now_gcd = now
				now_ind = i
		c.append(arr.pop(now_ind))
		crnt_gcd = now_gcd
	c = list(map(str, c))
	print(' '.join(c))


import math
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = []
	gcd = a[n - 1]
	ans.append(a[n - 1])
	a.pop(n - 1)
	for j in range(n - 1):
		b = []
		for i in range(len(a)):
			b.append(math.gcd(gcd, a[i]))
		maxindex = b.index(max(b))
		ans.append(a[maxindex])
		gcd = math.gcd(a[maxindex], gcd)
		a.pop(maxindex)
	for i in range(len(ans)):
		print(ans[i], end=' ')
	print()


import sys, collections, math
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))
for _ in range(inp()):
	n = inp()
	a = inpl()
	a.sort()
	seen = set()
	res = [a[-1]]
	seen.add(n - 1)
	ggg = a[-1]
	for _ in range(n - 1):
		mx = 0
		ans = -1
		for i in range(n):
			if i in seen:
				continue
			now = math.gcd(ggg, a[i])
			if now > mx:
				mx = now
				ans = i
		ggg = mx
		res.append(a[ans])
		seen.add(ans)
	print(*res)


def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)
for _ in range(int(input())):
	input()
	a = list(map(int, input().split()))
	b = []
	m = max(a)
	b.append(m)
	a.remove(m)
	bgcd = m
	maxgcd = 0
	maxelement = -1
	while len(a) > 0:
		for el in a:
			tempgcd = gcd(bgcd, el)
			if tempgcd > maxgcd:
				maxgcd = tempgcd
				maxelement = el
		b.append(maxelement)
		a.remove(maxelement)
		bgcd = maxgcd
		maxgcd = 0
		maxelement = -1
	for el in b:
		print(el, end=' ')
	print()


import io
import os
import sys
import math
fileno = sys.stdin.fileno()
input = io.BytesIO(os.read(fileno, os.fstat(fileno).st_size)).readline
T = int(input())
for t in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	A.sort(reverse=True)
	used = [False for i in range(N)]
	B = [A[0]]
	used[0] = True
	prefix_gcd = A[0]
	for i in range(1, N):
		best_gcd = 0
		best_j = None
		for j in range(1, N):
			if used[j]:
				continue
			current_gcd = math.gcd(prefix_gcd, A[j])
			if current_gcd > best_gcd:
				best_gcd = current_gcd
				best_j = j
				if best_gcd == prefix_gcd:
					break
		used[best_j] = True
		prefix_gcd = best_gcd
		B.append(A[best_j])
		if prefix_gcd == 1:
			for k in range(1, N):
				if not used[k]:
					B.append(A[k])
			break
	print(' '.join(map(str, B)))


def linput():
	return [int(i) for i in input().split()]

def nod(a, b):
	while a != 0 and b != 0:
		if a > b:
			a = a % b
		else:
			b = b % a
	return a + b
qwertyyyyyy = int(input())
for ______ in range(qwertyyyyyy):
	n = int(input())
	q = linput()
	qans = []
	qans.append(max(q))
	w = max(q)
	q.remove(w)
	ww = -1
	for j in range(n - 1):
		tt = 0
		for i in q:
			t = nod(w, i)
			if t > ww:
				ww = t
				tt = i
		w = ww
		qans.append(tt)
		q.remove(tt)
		ww = -1
	print(*qans)


import sys, bisect, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range
R = range

def Golf():
	(n, *t) = map(int, open(0).read().split())

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

def MI():
	return map(int, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def NLI(n):
	return [[int(i) for i in input().split()] for i in range(n)]

def NLI_(n):
	return [[int(i) - 1 for i in input().split()] for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RA():
	return map(int, open(0).read().split())

def RLI(n=8, a=1, b=10):
	return [random.randint(a, b) for i in range(n)]

def RI(a=1, b=10):
	return random.randint(a, b)

def Rtest(T):
	(case, err) = (0, 0)
	for i in range(T):
		inp = INP()
		(a1, ls) = naive(*inp)
		a2 = solve(*inp)
		if a1 != a2:
			print((a1, a2), inp)
			err += 1
		case += 1
	print('Tested', case, 'case with', err, 'errors')

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in R(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in R(base ** n):
		s = [tb // base ** bt % base for bt in R(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def YN(x):
	print(['NO', 'YES'][x])

def Yn(x):
	print(['No', 'Yes'][x])

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
l_alp = string.ascii_lowercase
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()

def primeFactor(N):
	(i, n) = (2, N)
	ret = {}
	(d, sq) = (2, 99)
	while i <= sq:
		k = 0
		while n % i == 0:
			(n, k, ret[i]) = (n // i, k + 1, k + 1)
		if k > 0 or i == 97:
			sq = int(n ** (1 / 2) + 0.5)
		if i < 4:
			i = i * 2 - 1
		else:
			(i, d) = (i + d, d ^ 6)
	if n > 1:
		ret[n] = 1
	return ret

def divisor(n):
	div = [1]
	for (i, j) in primeFactor(n).items():
		div = [i ** k * d for d in div for k in range(j + 1)]
	return div

def PrimeNumSet(N):
	M = int(N ** 0.5)
	seachList = [i for i in range(2, N + 1)]
	primes = []
	while seachList:
		if seachList[0] > M:
			break
		primes.append(seachList[0])
		tmp = seachList[0]
		seachList = [i for i in seachList if i % tmp != 0]
	return primes + seachList

def LCM(b, mo=10 ** 9 + 7):
	prs = PrimeNumSet(max(b))
	M = dict(zip(prs, [0] * len(prs)))
	for i in b:
		dc = primeFactor(i)
		for (j, k) in dc.items():
			M[j] = max(M[j], k)
	r = 1
	for (j, k) in M.items():
		if k != 0:
			r *= pow(j, k, mo)
			r %= mo
	return r
show_flg = False
show_flg = True
ans = 0
for _ in range(I()):
	n = I()
	a = LI()
	a = sorted(a)
	m = a.pop()
	ans = [m]
	v = [0] * (n - 1)
	ko = [[] for i in range(m + 1)]
	for i in range(n - 1):
		c = a[i]
		for j in divisor(c):
			ko[j] += (i,)
	ans = []
	g = m
	while g > 1:
		dm = sorted(divisor(g))[::-1]
		tmp = []
		for d in dm:
			if ko[d]:
				for x in ko[d]:
					if v[x] == 0:
						v[x] = 1
						tmp += (x,)
				if tmp:
					g = gcd(g, a[tmp[0]])
					ans += tmp
					break
		if sum(v) == n - 1:
			break
	t = [m] + [a[i] for i in ans]
	print(*t)


try:
	from math import gcd
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = [int(i) for i in input().split(' ')]
		m = max(a)
		final = []
		while a:
			sets = max(((gcd(m, val), val) for val in a))
			a.remove(sets[1])
			final.append(sets[1])
			m = sets[0]
		print(*final)
except:
	pass


from math import gcd
for tt in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	ans = []
	ans.append(a.pop())
	cur = ans[0]
	for i in range(n - 1):
		best = 0
		l = 0
		for j in a:
			if gcd(j, cur) >= l:
				l = gcd(j, cur)
				best = j
		ans.append(best)
		a.remove(best)
		cur = l
	print(*ans)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	if len(l) == 1:
		print(l[0])
		continue
	g = [[gcd(l[i], l[j]) for j in range(n)] for i in range(n)]
	for i in range(n):
		g[i][i] = -1
	maxm = max(l)
	gg = int(maxm)
	left = [i for i in range(n)]
	left.remove(l.index(maxm))
	b = [maxm]
	while len(left) > 0:
		maxm = 0
		ans = -1
		for k in left:
			if gcd(l[k], gg) > maxm:
				maxm = int(gcd(l[k], gg))
				ans = int(k)
		b.append(l[ans])
		left.remove(ans)
		gg = int(maxm)
	print(' '.join(map(str, b)))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	g = a[0]
	i = 1
	while i < n:
		jj = 0
		for j in range(i, n):
			if gcd(g, a[j]) > jj:
				jj = gcd(g, a[j])
				ind = j
		(a[i], a[ind]) = (a[ind], a[i])
		g = jj
		i += 1
	print(*a)


import math
for t in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	num.sort()
	val = num.pop()
	out = [val]
	while num:
		gcd = 0
		ele = 0
		for i in range(len(num)):
			v = math.gcd(val, num[i])
			if v > gcd:
				gcd = v
				ele = i
		val = gcd
		out.append(num.pop(ele))
	print(*out)


import sys
input = sys.stdin.readline
from fractions import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(item) for item in input().split()]
	gcd_val = max(a)
	ans = [gcd_val]
	a.remove(gcd_val)
	while a:
		maxs = []
		rest = []
		ngcd = 0
		for item in a:
			g = gcd(item, gcd_val)
			if g > ngcd:
				rest += maxs
				maxs = [item]
				ngcd = gcd(item, gcd_val)
			elif g == ngcd:
				maxs.append(item)
			else:
				rest.append(item)
		gcd_val = ngcd
		ans += maxs
		a = rest[:]
	print(*ans)


from sys import *
from math import gcd
t = int(stdin.readline().strip())
for k in range(t):
	n = int(stdin.readline().strip())
	a = list(map(int, stdin.readline().split()))
	a.sort(reverse=True)
	currentgcd = a[0]
	start = 1
	for i in range(1, n):
		bestgcd = 0
		index = -1
		for j in range(i, n):
			guess = gcd(currentgcd, a[j])
			if currentgcd == guess:
				index = j
				break
			if bestgcd < gcd(currentgcd, a[j]):
				index = j
				bestgcd = gcd(currentgcd, a[j])
		(a[i], a[index]) = (a[index], a[i])
		currentgcd = gcd(currentgcd, a[i])
		if currentgcd == 1:
			break
	print(' '.join(map(str, a)))


from math import gcd
from collections import Counter
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	max1 = max(lis)
	output = [max1]
	dic = Counter(lis)
	dic[max1] -= 1
	if dic[max1] == 0:
		del dic[max1]
	gcd1 = max1
	while len(output) != len(lis):
		max1 = 0
		for i in dic:
			if gcd(gcd1, i) > max1:
				max1 = gcd(gcd1, i)
				element = i
		dic[element] -= 1
		output.append(element)
		if dic[element] == 0:
			del dic[element]
		gcd1 = max1
	for i in output:
		print(i, end=' ')
	print()


import sys
import math
fast_reader = sys.stdin.readline
fast_writer = sys.stdout.write

def input():
	return fast_reader().strip()
for T in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	m = max(a)
	count = 1
	ans = [m]
	used = [False for i in range(n)]
	for i in range(n):
		if a[i] == m:
			used[i] = True
			break
	for k in range(1, n):
		mx = 1
		ind = 0
		for i in range(n):
			if used[i] == False and math.gcd(a[i], m) >= mx:
				mx = math.gcd(a[i], m)
				el = a[i]
				count = 1
				ind = i
		ans.append(el)
		used[ind] = True
		m = mx
	for i in range(n):
		print(ans[i], end=' ')
	print()


import sys
input = sys.stdin.buffer.readline
from math import gcd

def main():
	n = int(input())
	alst = list(map(int, input().split()))
	alst.sort(reverse=True)
	used = [False for _ in range(n)]
	ans = [alst[0]]
	used[0] = True
	num = alst[0]
	for _ in range(n - 1):
		pos = 0
		tt = 0
		for (i, a) in enumerate(alst):
			if used[i]:
				continue
			g = gcd(num, a)
			if g > tt:
				tt = g
				pos = i
		ans.append(alst[pos])
		used[pos] = True
		num = tt
	print(*ans)
for _ in range(int(input())):
	main()


def computeGCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	pivot = max(arr)
	ans = []
	for i in range(n):
		m = -1
		index = -1
		for j in range(len(arr)):
			if computeGCD(pivot, arr[j]) > m:
				m = computeGCD(pivot, arr[j])
				index = j
		ans.append(arr[index])
		pivot = computeGCD(pivot, arr[index])
		arr.pop(index)
	for i in ans:
		print(i, end=' ')
	print()


def nwd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a
for _ in range(int(input())):
	n = int(input())
	liczby = sorted(list(map(int, input().split())))
	wynik = []
	wynik.append(liczby[-1])
	liczby = liczby[:-1]
	nwdb = wynik[0]
	for x in range(1, n):
		maks = 0
		best = 0
		for z in range(len(liczby)):
			cos = nwd(nwdb, liczby[z])
			if cos > maks:
				best = z
				maks = cos
		wynik.append(liczby[best])
		nwdb = nwd(nwdb, wynik[-1])
		del liczby[best]
	print(*wynik)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	preg = max(arr)
	visit = [0] * n
	visit[arr.index(preg)] = 1
	print(preg, end=' ')
	for i in range(n - 1):
		maxg = 0
		temp = 0
		for j in range(n):
			if visit[j] == 0 and maxg <= gcd(preg, arr[j]):
				temp = j
				maxg = gcd(preg, arr[j])
		print(arr[temp], end=' ')
		preg = gcd(preg, arr[temp])
		visit[temp] = 1
	print()


import sys

def gcd(a, b):
	x = min(a, b)
	y = max(a, b)
	if x == 0:
		return y
	else:
		return gcd(y % x, x)
t = int(input())
while t > 0:
	t -= 1
	n = int(sys.stdin.readline())
	input = sys.stdin.readline()
	arr = list(map(int, input.split()))
	arr.sort(reverse=True)
	cur_gcd = arr[0]
	index = 1
	while cur_gcd > 1 and index < n:
		max_gcd = gcd(cur_gcd, arr[index])
		pos = index
		for i in range(index + 1, n):
			value = gcd(cur_gcd, arr[i])
			if value > max_gcd:
				max_gcd = value
				pos = i
		cur_gcd = max_gcd
		(arr[index], arr[pos]) = (arr[pos], arr[index])
		index += 1
	print(*arr)


import sys
import os
import math
import copy
from math import gcd
from bisect import bisect
from io import BytesIO, IOBase
from math import sqrt, floor, factorial, gcd, log, ceil
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
from itertools import accumulate

def Int():
	return int(sys.stdin.readline())

def Mint():
	return map(int, sys.stdin.readline().split())

def Lstr():
	return list(sys.stdin.readline().strip())

def Str():
	return sys.stdin.readline().strip()

def Mstr():
	return map(str, sys.stdin.readline().strip().split())

def List():
	return list(map(int, sys.stdin.readline().split()))

def Hash():
	return dict()

def Mod():
	return 1000000007

def Ncr(n, r, p):
	return fact[n] * (ifact[r] * ifact[n - r] % p) % p

def Most_frequent(list):
	return max(set(list), key=list.count)

def Mat2x2(n):
	return [List() for _ in range(n)]

def Lcm(x, y):
	return x * y // gcd(x, y)

def dtob(n):
	return bin(n).replace('0b', '')

def btod(n):
	return int(n, 2)

def common(l1, l2):
	return set(l1).intersection(l2)

def solution():
	for _ in range(Int()):
		n = Int()
		a = List()
		a.sort(reverse=True)
		ans = [a[0]]
		vis = [0] * n
		vis[0] = 1
		start = a[0]
		for i in range(1, n):
			MAX = 0
			prev = 0
			for j in range(n):
				if vis[j] == 0:
					tmp = gcd(start, a[j])
					if MAX <= tmp:
						MAX = tmp
						prev = j
			vis[prev] = 1
			ans.append(a[prev])
			start = MAX
		print(*ans)
solution()


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	data = [int(x) for x in input().split()]
	ans = [max(data)]
	data.remove(ans[0])
	temp = ans[0]
	for q in range(n - 1):
		pos = 0
		maximum = 0
		for w in range(len(data)):
			t = gcd(temp, data[w])
			if t >= maximum:
				if t == maximum:
					if data[pos] > data[w]:
						pos = w
				else:
					maximum = t
					pos = w
		ans.append(data[pos])
		temp = maximum
		data.pop(pos)
	for q in ans:
		print(q, end=' ')
	print()


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	ans = [0]
	g = 0
	seti = {0}
	for i in range(1, n):
		g = gcd(g, l[ans[i - 1]])
		z = 0
		maxi = 0
		ind = -1
		for j in range(n):
			if j not in seti:
				if gcd(g, l[j]) > maxi:
					maxi = gcd(g, l[j])
					ind = j
		seti.add(ind)
		ans.append(ind)
	la = [l[i] for i in ans]
	print(*la)


from math import gcd
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	b = []
	curr = max(arr)
	b.append(curr)
	arr.remove(curr)
	cd = curr
	while arr:
		curr = max(arr, key=lambda x: gcd(x, cd))
		b.append(curr)
		arr.remove(curr)
		cd = gcd(cd, curr)
	ans.append(b)
for el in ans:
	print(' '.join(list(map(str, el))))


from collections import Counter
from math import gcd
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	ans = [b[-1]]
	maxi = b[-1]
	b = b[:-1]
	while b:
		maxgcd = 0
		x = 0
		for k in range(len(b)):
			if gcd(maxi, b[k]) > maxgcd:
				x = k
				maxgcd = gcd(maxi, b[k])
		ans.append(b[x])
		maxi = maxgcd
		b.pop(x)
	print(*ans)


from math import gcd
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.reverse()
	g = a[0]
	for i in range(1, n):
		m = 0
		s = i
		for j in range(i, n):
			gc = gcd(g, a[j])
			if gc > m:
				s = j
				m = gc
		(a[i], a[s]) = (a[s], a[i])
		g = m
	print(*a, sep=' ')


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	arr = sorted([int(p) for p in input().split()], reverse=True)
	final = [arr[0]]
	ele = 0
	g = arr[0]
	arr.pop(0)
	while arr:
		ele = 0
		curr = None
		for i in range(len(arr)):
			prev = ele
			ele = max(ele, gcd(arr[i], g))
			if prev != ele:
				curr = arr[i]
		final.append(curr)
		arr.remove(curr)
		g = gcd(curr, g)
	print(*final)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve(case):
	n = int(inp())
	a = lis()
	ans = []
	a = sorted(a)[::-1]
	ans.append(a[0])
	curr = a[0]
	a = a[1:]
	while len(ans) != n:
		mini = 0
		val = -1
		for i in range(len(a)):
			if gcd(curr, a[i]) > mini:
				mini = gcd(curr, a[i])
				val = a[i]
		a.remove(val)
		ans.append(val)
		curr = gcd(curr, val)
	print(' '.join((str(ans[i]) for i in range(len(ans)))))
testcase(int(inp()))


def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	a = []
	a.append(max(arr))
	arr.remove(max(arr))
	k = len(arr)
	l = len(arr) - 1
	prev = a[0]
	for i in range(1, k + 1):
		m = 0
		ans = 0
		for j in range(l + 1):
			if gcd(prev, arr[j]) == max(m, gcd(prev, arr[j])):
				m = gcd(prev, arr[j])
				ans = arr[j]
		a.append(ans)
		arr.remove(ans)
		prev = m
		l -= 1
	for i in range(len(a)):
		print(a[i], ' ', end='')


import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().rstrip().split()))
	a.sort()
	g = a[-1]
	ans = [g]
	mx = 0
	ind = -1
	v = [0] * n
	v[-1] = 1
	ct = 0
	for i in range(1, n):
		ct = 0
		for j in range(n):
			if v[j] == 0:
				if ct == 0:
					g1 = math.gcd(a[j], g)
					ind = j
					ct += 1
				else:
					t = math.gcd(a[j], g)
					if t > g1:
						g1 = t
						ind = j
		g = g1
		v[ind] = 1
		ans.append(a[ind])
	for i in ans:
		print(i, end=' ')
	print()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	check = [False] * n
	b = [0] * n
	b[0] = max(a)
	check[a.index(max(a))] = True
	now = b[0]
	for i in range(1, n):
		max1 = [-1, -1]
		for j in range(n):
			if not check[j]:
				if max1[0] < gcd(a[j], now):
					max1 = [gcd(a[j], now), j]
		check[max1[1]] = True
		b[i] = a[max1[1]]
		now = max1[0]
	print(' '.join(map(str, b)))


from sys import stdin, stdout

def GCD(a, b):
	if a == 0:
		return b
	return GCD(b % a, a)

def find(arr, N):
	G = 0
	A = []
	while arr:
		K = [GCD(G, i) for i in arr]
		x = K.index(max(K))
		A.append(arr[x])
		G = max(K)
		del arr[x]
	return ' '.join(map(str, A))

def main():
	for _ in range(int(stdin.readline())):
		N = int(stdin.readline())
		arr = list(map(int, stdin.readline().split()))
		print(find(arr, N))
main()


import sys, os, io
from math import gcd
input = sys.stdin.readline
T = int(input())
ans = [0] * T
for t in range(T):
	N = int(input())
	ans[t] = [0] * N
	A = list(map(int, input().split()))
	old_g = max(A)
	ans[t][0] = old_g
	A.remove(old_g)
	for i in range(1, N):
		max_g = 0
		for a in A:
			new_g = gcd(a, old_g)
			if new_g > max_g:
				max_g = new_g
				val = a
		ans[t][i] = val
		A.remove(val)
		old_g = max_g
for a in ans:
	print(*a)


import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	c = Counter(a)
	ma = max(a)
	l = [ma]
	c[ma] -= 1
	if c[ma] == 0:
		del c[ma]
	g = ma
	for i1 in range(1, n):
		cur = [0, 0]
		for j in c:
			g1 = math.gcd(g, j)
			if g1 > cur[0]:
				cur = [g1, j]
		c[cur[1]] -= 1
		g = cur[0]
		l.append(cur[1])
		if c[cur[1]] == 0:
			del c[cur[1]]
	print(*l)


def gcd(a, b):
	while b != 0:
		(a, b) = (b, a % b)
	return a
t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	b = [0] * n
	mi = 0
	while i < n:
		if a[i] > a[mi]:
			mi = i
		i += 1
	b[0] = a[mi]
	a[mi] = 0
	cg = b[0]
	i = 1
	while i < n:
		ci = 0
		cans = 0
		j = 0
		while j < n:
			z = gcd(a[j], cg)
			if a[j] and z > cans:
				cans = z
				ci = j
			j += 1
		b[i] = a[ci]
		cg = cans
		a[ci] = 0
		i += 1
	for x in b:
		print(x, end=' ')
	print()
	t -= 1


def gcd(a, b):
	while a * b:
		a %= b
		(a, b) = (b, a)
	return a
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = []
	for i in range(n):
		a[i] = [a[i]] * 2
	for i in range(n):
		m = c = 0
		for j in range(n):
			if a[j][0] > m:
				m = a[j][0]
				c = j
		d.append(a[c][1])
		a[c][0] = 0
		for j in range(n):
			if a[j][0]:
				a[j][0] = gcd(m, a[j][0])
	print(' '.join(map(str, d)))


import time, math as mt, bisect as bs, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * (2 * 10 ** 5 + 5)
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(2 * 10 ** 5 + 5):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return

def readTree(n, e):
	adj = [set() for i in range(n + 1)]
	for i in range(e):
		(u1, u2) = IP()
		adj[u1].add(u2)
	return adj
mod = 10 ** 9 + 7

def solve():
	n = II()
	a = L()
	a.sort()
	mx = a[-1]
	ans = [mx]
	cur = mx
	d = {}
	d[n - 1] = 1
	last = cur
	for j in range(cur, 0, -1):
		if cur % j == 0 and last % j == 0:
			for i in range(n - 1, -1, -1):
				if a[i] % j == 0:
					if d.get(i, -1) == -1:
						ans.append(a[i])
						cur = a[i]
						d[i] = 1
						last = j
	print(*ans)
	return
t = II()
for i in range(t):
	solve()


def computeGCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for _ in range(int(input())):
	n = int(input())
	arr = [int(j) for j in input().split()]
	res = []
	res.append(max(arr))
	arr.remove(max(arr))
	count = 0
	while count < n - 1:
		if count != 0:
			gcd = computeGCD(res[0], res[1])
			for i in range(2, len(res)):
				gcd = computeGCD(gcd, res[i])
		else:
			gcd = res[0]
		x = computeGCD(gcd, arr[0])
		item = arr[0]
		for i in range(1, len(arr)):
			temp = computeGCD(gcd, arr[i])
			if temp > x:
				x = temp
				item = arr[i]
		res.append(item)
		arr.remove(item)
		count += 1
	print(*res)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	m = max(a)
	p = []
	f = []
	i = 1
	while i * i <= m:
		if m % i == 0:
			f.append(i)
			if m // i != i:
				f.append(m // i)
		i += 1
	f.sort()
	seen = {}
	last = 0
	for i in reversed(f):
		if last % i != 0:
			continue
		for j in a:
			if j % i == 0:
				if j in seen and seen[j] != i:
					continue
				seen[j] = i
				p.append(j)
				last = i
	print(*p)


from __future__ import division, print_function
import sys
input = sys.stdin.readline

def gcd(x, y):
	if not x:
		return y
	if not y:
		return x
	return gcd(y, x % y)

def main():
	for _ in range(int(input())):
		n = int(input())
		a = [int(x) for x in input().split()]
		f = [0] * (n + 5)
		a.sort(reverse=True)
		ans = [a[0]]
		f[0] = 1
		g = a[0]
		while len(ans) != n:
			mx = 0
			pos = -1
			for i in range(n):
				if f[i] == 0:
					if gcd(g, a[i]) > mx:
						mx = gcd(g, a[i])
						pos = i
			f[pos] = 1
			ans.append(a[pos])
			g = gcd(g, a[pos])
		print(*ans)
main()


from math import gcd
t = int(input())
for i in range(t):
	n = int(input())
	nums = sorted(map(int, input().split()), reverse=True)
	out = [nums[0]]
	g = nums.pop(0)
	for j in range(n - 1):
		cp = -1
		cg = -1
		for d in range(n - 1 - j):
			cur = gcd(g, nums[d])
			if cur > cg:
				cg = cur
				cp = d
		out.append(nums[cp])
		del nums[cp]
		g = cg
	print(' '.join(map(str, out)))


from sys import stdin, stdout
from collections import Counter
from itertools import permutations
import bisect
import math
I = lambda : map(int, stdin.readline().split())
I1 = lambda : stdin.readline()
for _ in range(int(I1())):
	n = int(I1())
	a = list(I())
	m = max(a)
	ind = a.index(m)
	l = [m]
	a[ind] = -1
	g = l[0]
	for i in range(1, n):
		c = 0
		m = -1
		for j in range(n):
			if a[j] == -1:
				continue
			else:
				d = math.gcd(g, a[j])
				if d > c:
					c = d
					m = j
		l.append(a[m])
		a[m] = -1
		g = c
	for x in l:
		print(x, end=' ')
	print()


def g(a, b):
	if b == 0:
		return a
	return g(b, a % b)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	m = -1
	j = 0
	while i < n:
		if a[i] > m:
			j = i
			m = a[i]
		i += 1
	b = [j]
	ans = a[j]
	for _ in range(n - 1):
		m = -1
		j = 0
		for i in range(n):
			if i not in b:
				if g(ans, a[i]) > m:
					j = i
					m = g(ans, a[i])
		b.append(j)
		ans = g(ans, a[j])
	c = []
	for i in range(n):
		c.append(a[b[i]])
	print(*c)


import copy
N = int(input())
Ans = []
for i in range(N):
	A = int(input())
	B = list(map(int, input().split()))
	T = []
	M = max(B)
	used = [0] * (M + 1)
	for j in range(A):
		used[B[j]] += 1
	T.append(M)
	used[M] -= 1
	P = []
	for j in range(M + 1, 0, -1):
		if M % j == 0:
			P.append(j)
	while True:
		if len(T) == A:
			break
		c = 0
		for j in range(len(P)):
			if c == 1:
				break
			for div in range(P[j], M + 1, P[j]):
				if used[div] != 0:
					c = 1
					for k in range(used[div]):
						T.append(div)
						used[div] -= 1
		L = P.copy()
		for div in L:
			if T[-1] % div != 0:
				P.remove(div)
	Ans.append(T)
for i in Ans:
	for j in i:
		print(j, end=' ')
	print()


import functools

def gcd(a, b):
	return gcd(b, a % b) if b != 0 else a

def solve_seq(seq, numbers):
	if not numbers:
		return seq
	seqgcd = functools.reduce(gcd, seq)
	(maxarg, maxgcd) = (-1, -1)
	for n in numbers:
		curgcd = gcd(n, seqgcd)
		if curgcd > maxgcd:
			maxgcd = curgcd
			maxarg = n
	numbers.remove(maxarg)
	return solve_seq(seq + [maxarg], numbers)

def solve_numbers(numbers):
	numbers = list(reversed(sorted(numbers)))
	solved = solve_seq([numbers[0]], numbers[1:])
	print(' '.join(map(str, solved)))

def solve():
	count = int(input())
	for i in range(count):
		_ = input()
		numbers = list(map(int, input().split()))
		solve_numbers(numbers)
solve()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = [int(num) for num in input().split(' ')]
	a = max(arr)
	ans = [a]
	c = [a]
	arr.remove(a)
	while len(c) <= n - 1:
		x = []
		for item in arr:
			x.append([gcd(c[-1], item), item])
		x.sort(key=lambda x: x[0], reverse=True)
		c.append(x[0][0])
		arr.remove(x[0][1])
		ans.append(x[0][1])
	for item in ans:
		print(item, end=' ')
	print('')


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
input = lambda : sys.stdin.buffer.readline().rstrip()

def primeFactors(n):
	a = []
	while n % 2 == 0:
		a.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			a.append(i)
			n = n / i
	if n > 2:
		a.append(n)
	return a
for _ in range(int(input())):
	q = int(input())
	w = sorted(list(map(int, input().split())))
	t = max(w)
	l = [t]
	y = t
	k = 0
	w.pop(-1)
	while len(w):
		t = 0
		for i in range(len(w)):
			a = math.gcd(y, w[i])
			if a >= t:
				t = a
				k = i
		l.append(w[k])
		y = t
		w.pop(k)
	print(*l)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		a = LI()
		s = set(range(n))
		g = max(a)
		r = []
		while s:
			m = 0
			mm = 0
			for c in s:
				h = math.gcd(g, a[c])
				if m < h:
					m = h
					mm = c
			r.append(a[mm])
			s.remove(mm)
			g = m
		rr.append(JA(r, ' '))
	return JA(rr, '\n')
print(main())


import math
gcd = math.gcd
t = int(input())
for _ in range(t):
	n = int(input())
	l1 = [int(x) for x in input().split()]
	old = max(l1)
	ans = []
	for i in range(n):
		l2 = [gcd(int(x), old) for x in l1]
		new = l1[l2.index(max(l2))]
		ans.append(new)
		l1.remove(new)
		old = gcd(old, new)
	print(*ans)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	res = []
	max_num = max(arr)
	res.append(max_num)
	ind = arr.index(max_num)
	arr[ind] = 0
	prev_gcd = max_num
	for _ in range(n - 1):
		(max_num, max_gcd, max_num_ind) = (0, 0, 0)
		for (ind, num) in enumerate(arr):
			if num == 0:
				continue
			else:
				gcd_x = gcd(prev_gcd, num)
				if gcd_x > max_gcd:
					max_gcd = gcd_x
					max_num = num
					max_num_ind = ind
		res.append(max_num)
		arr[max_num_ind] = 0
		prev_gcd = max_gcd
	temp = list(map(str, res))
	print(' '.join(temp))


from math import gcd
q = int(input())
for _ in range(q):
	n = int(input())
	s = list(map(int, input().split()))
	s.sort()
	c = [s[-1]]
	seen = {n - 1}
	y = s[-1]
	while len(c) < n:
		(tmp, res, ind) = (0, 0, 0)
		for i in range(n):
			if i not in seen:
				x = gcd(y, s[i])
				if x > tmp:
					(tmp, res, ind) = (x, s[i], i)
		c.append(res)
		seen.add(ind)
		y = tmp
	print(*c)


from math import gcd
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [max(a)]
	gr = ans[-1]
	vis = [0] * len(a)
	while len(ans) != n + 1:
		mx = -1
		mx_ind = -1
		for i in range(len(a)):
			if vis[i] != 1:
				tmp = gcd(gr, a[i])
				if mx < tmp:
					mx = tmp
					mx_ind = i
		gr = mx
		vis[mx_ind] = 1
		ans.append(a[mx_ind])
	ans.pop(0)
	print(*ans)


import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // gcd(a, b)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			high = mid
		else:
			low = mid + 1
	return low

def check(size, w, h, n):
	return size // w * (size // h) >= n
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis

def solve():
	n = int(input())
	a = list(read())
	vis = [False for _ in range(n)]
	ans = []
	mgcd = 0
	for i in range(n):
		ind = 0
		m = 0
		for j in range(n):
			if vis[j] == False and math.gcd(a[j], mgcd) > m:
				m = math.gcd(a[j], mgcd)
				ind = j
		mgcd = m
		ans.append(a[ind])
		vis[ind] = True
	print(*ans)
for _ in range(int(input())):
	solve()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	note = [[0] * 1001 for i in range(n)]
	for i in range(n):
		for j in range(1001):
			note[i][j] = gcd(j, A[i])
	x = 0
	ans = [0] * n
	for i in range(n):
		m = 0
		k = 0
		for j in range(n):
			if A[j] and note[j][x] > m:
				m = note[j][x]
				k = j
		ans[i] = A[k]
		A[k] = 0
		x = m
	print(*ans)


import sys
import math
import collections
import bisect
import itertools
import decimal
import copy
import heapq
INF = 10 ** 20
MOD = 10 ** 9 + 7
ni = lambda : int(sys.stdin.readline().rstrip())
ns = lambda : map(int, sys.stdin.readline().rstrip().split())
na = lambda : list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda : list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))

def main():
	t = ni()
	for _ in range(t):
		n = ni()
		a = na()
		m = max(a)
		c = collections.Counter(a)
		res = []
		max_gcd = m
		while len(c):
			t_m = 0
			t_max_gcd = 0
			for k in c.keys():
				t_gcd = math.gcd(max_gcd, k)
				if t_gcd > t_max_gcd:
					t_max_gcd = t_gcd
					t_m = k
			max_gcd = t_max_gcd
			m = t_m
			for __ in range(c[m]):
				res.append(m)
			del c[m]
		print(*res, sep=' ')
main()


import io, os
inp = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inar = lambda : list(map(int, inp().split()))
inin = lambda : int(inp())
inst = lambda : inp().decode().strip()
from math import gcd
_T_ = inin()
for _t_ in range(_T_):
	n = inin()
	a = inar()
	a.sort(reverse=True)
	na = []
	ta = []
	for i in a:
		if i == a[0]:
			na.append(i)
		else:
			ta.append(i)
	cgcd = a[0]
	while len(na) < n:
		mg = 0
		for i in ta:
			mg = max(mg, gcd(i, cgcd))
		temp = []
		for i in ta:
			if gcd(i, cgcd) == mg:
				na.append(i)
			else:
				temp.append(i)
		ta = temp
		cgcd = gcd(cgcd, mg)
	print(*na)


import sys
from math import gcd
input = sys.stdin.readline
for _ in range(int(input())):
	N = int(input())
	a = list(map(int, input().split()))
	mx = max(a)
	table = [0] * (mx + 1)
	for x in a:
		table[x] += 1
	res = [mx]
	table[mx] -= 1
	g = mx
	for _ in range(N - 1):
		y = 0
		for x in range(1, mx + 1):
			if table[x] == 0:
				continue
			if y == 0 or gcd(g, x) > gcd(g, y):
				y = x
		table[y] -= 1
		res.append(y)
		g = gcd(g, y)
	print(*res)


import os
from io import BytesIO, IOBase
import sys
from math import gcd

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		a.sort()
		d = a[-1]
		print(a[-1], end=' ')
		b = [False for i in range(n)]
		b[-1] = True
		for i in range(1, n):
			(mx, p) = (0, 0)
			for j in range(n - 2, -1, -1):
				if not b[j] and gcd(a[j], d) > mx:
					mx = gcd(a[j], d)
					p = j
			b[p] = True
			print(a[p], end=' ')
			d = gcd(d, a[p])
		print()
	return
BUFSIZE = 1048576

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from collections import Counter
from collections import defaultdict as dc
for _ in range(N()):
	n = N()
	a = RLL()
	dd = Counter(a)
	aa = list(dd.keys())
	k = max(aa)
	res = [k]
	now = []
	dic = dc(set)
	for p in range(k, 0, -1):
		if k % p == 0:
			now.append(p)
			for x in aa:
				if x % p == 0:
					dic[p].add(x)
	nums = {k}
	for p in now:
		if dic[p] >= nums:
			res += list(dic[p] - nums)
			nums = dic[p]
	ans = []
	for x in res:
		ans += [x] * dd[x]
	print_list(ans)


import os
import sys
from io import BytesIO, IOBase
import math
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort(reverse=True)
	raj1 = [l[0]]
	newv = [0] * n
	newv[0] = 1
	ext = l[0]
	bbb = list()
	for i in range(1, n):
		mg = 0
		bbb.append(math.gcd(i, 4))
		p = 0
		for j in range(n):
			if newv[j]:
				continue
				ni = 2
				ni = ni * 2
			if mg < math.gcd(l[j], ext):
				mg = math.gcd(l[j], ext)
				bbb.append(3)
				p = j
		if mg == 0:
			break
		ext = mg
		newv[p] = 1
		raj1.append(l[p])
		x = list()
		x = ext
	nu = list()
	for i in range(n):
		if newv[i] == 0:
			raj1.append(l[i])
			nu.append(l[i])
	print(*raj1)


from math import gcd as _gcd
import sys as _sys

def main():
	t = int(input())
	for i in range(t):
		(n,) = _read_ints()
		a = tuple(_read_ints())
		b = find_b(a)
		print(*b)

def _read_line():
	result = _sys.stdin.readline()
	assert result[-1] == '\n'
	return result[:-1]

def _read_ints():
	return map(int, _read_line().split(' '))

def find_b(a):
	a = list(a)
	b = []
	if len(a) == 0:
		return b
	first_element = max(a)
	b.append(first_element)
	a.remove(first_element)
	curr_gcd = first_element
	while len(a) != 0:
		next_element = max(a, key=lambda x: _gcd(curr_gcd, x))
		b.append(next_element)
		a.remove(next_element)
		curr_gcd = _gcd(curr_gcd, next_element)
	return b
main()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	b = [-1] * n
	b[0] = a[0]
	a[0] = -1
	g = b[0]
	for i in range(1, n):
		g2 = 1
		ind = -1
		for j in range(n):
			if a[j] < 0:
				continue
			g1 = math.gcd(g, a[j])
			if g1 > g2:
				g2 = g1
				ind = j
		if ind == -1:
			break
		b[i] = a[ind]
		a[ind] = -1
		g = g2
	for i in b:
		if i > -1:
			print(i, end=' ')
	for i in a:
		if i > -1:
			print(i, end=' ')
	print()


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = int(input())
for _ in range(t):
	n = int(input())
	s = list(map(int, input().split()))
	p = max(s)
	curr = p
	while len(s) > 0:
		m = 0
		num = 0
		for i in s:
			if gcd(curr, i) > m:
				m = gcd(curr, i)
				num = i
		print(num, end=' ')
		curr = m
		s.remove(num)
	print()


import math
t = int(input())
for case in range(t):
	n = int(input())
	a = [int(s) for s in input().split(' ')]
	x = max(a)
	r = [x]
	a.remove(x)
	gd = x
	loop_bool = True
	while loop_bool:
		loop_bool = False
		max_elem = 1
		for item in a:
			if math.gcd(gd, item) > max_elem:
				max_elem = math.gcd(gd, item)
				x = item
				loop_bool = True
		if loop_bool:
			gd = max_elem
			r.append(x)
			a.remove(x)
	print(' '.join([str(s) for s in r + a]))


from math import gcd
for _ in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	index = num.index(max(num))
	result = [num[index]]
	num[index] = -1
	value = result[0]
	for i in range(1, n):
		max_value = -1
		index = -1
		for j in range(n):
			if num[j] == -1:
				continue
			else:
				temp = gcd(value, num[j])
				if temp > max_value:
					max_value = temp
					index = j
		value = gcd(value, num[index])
		result.append(num[index])
		num[index] = -1
	print(' '.join(map(str, result)))


import sys
readline = sys.stdin.readline
INF = 2 ** 62 - 1

def read_int():
	return int(readline())

def read_int_n():
	return list(map(int, readline().split()))

def read_float():
	return float(readline())

def read_float_n():
	return list(map(float, readline().split()))

def read_str():
	return readline().strip()

def read_str_n():
	return readline().strip().split()

def ep(*args):
	print(*args, file=sys.stderr)

def mt(f):
	import time

	def wrap(*args, **kwargs):
		s = time.perf_counter()
		ret = f(*args, **kwargs)
		e = time.perf_counter()
		ep(e - s, 'sec')
		return ret
	return wrap
import math
from itertools import combinations
from collections import Counter

def slv(N, A):
	if N == 1:
		return A
	ans = []
	ac = Counter(A)
	g = 0
	for _ in range(N):
		mg = (-1, -1)
		for (k, v) in ac.items():
			if v == 0:
				continue
			mg = max(mg, (math.gcd(g, k), k))
		ans.append(mg[1])
		ac[mg[1]] -= 1
		g = mg[0]
	return ans

def main():
	for _ in range(read_int()):
		N = read_int()
		A = read_int_n()
		print(*slv(N, A))
main()


from collections import defaultdict
from math import gcd
t = int(input())
for test in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	maxi = max(a)
	ans = []
	cur = 0
	while a:
		mx = 0
		idx = -1
		for i in range(len(a)):
			x = gcd(a[i], cur)
			if x > mx:
				mx = x
				idx = i
		cur = mx
		ans.append(a[idx])
		a.pop(idx)
	print(*ans)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
ans = 0

def pr_list(a):
	print(*a, sep=' ')

def swap(a, b):
	temp = a
	a = b
	b = temp
	return [a, b]

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	stack = []
	hashm = {}
	arr = []
	heapq.heapify(arr)
	for test in range(tests):
		n = inp()
		a = inlt()
		ans = []
		a.sort(reverse=True)
		done = [0 for i in range(n)]
		ans.append(a[0])
		curr = ans[0]
		done[0] = 1

		def gcd(a, b):
			if a > b:
				[a, b] = swap(a, b)
			if b % a == 0:
				return a
			return gcd(b % a, a)
		for i in range(1, n):
			dum = -1 * sys.maxsize
			target = 0
			for j in range(n):
				if done[j] == 0:
					t = gcd(curr, a[j])
					if t > dum:
						dum = t
						target = j
			done[target] = 1
			ans.append(a[target])
			curr = gcd(curr, a[target])
		pr_list(ans)
main()


import math
I = lambda : map(int, input().split())
for _ in [0] * int(input()):
	n = int(input())
	a = list(I())
	x = curgcd = max(a)
	a.remove(x)
	b = [x] + [0] * (n - 1)
	for i in range(1, n):
		k = ind = uear = 0
		for y in a:
			u = math.gcd(y, curgcd)
			if u > uear:
				uear = u
				num = y
				ind = k
			k = k + 1
		b[i] = num
		del a[ind]
		curgcd = uear
		if uear == 1:
			b = b[:i + 1] + a
			break
	print(*b)


from math import gcd
T = int(input())
for t in range(T):
	n = int(input())
	A = [int(i) for i in input().split()]
	cur_grade = dict()
	visited = [False] * n
	max_A = max(A)
	B = []
	for i in range(n):
		if A[i] == max_A:
			visited[i] = True
			B.append(A[i])
	prev_best_grad = B[-1]
	while len(B) < n:
		best_grade = 0
		for i in range(n):
			if not visited[i]:
				cur_grade[i] = gcd(prev_best_grad, A[i])
				best_grade = max(best_grade, cur_grade[i])
		for i in range(n):
			if not visited[i] and cur_grade[i] == best_grade:
				visited[i] = True
				B.append(A[i])
		prev_best_grad = best_grade
	print(*B)


def gcd(a, b):
	if a < b:
		(a, b) = (b, a)
	while b > 1:
		if a % b == 0:
			return b
		(a, b) = (b, a % b)
	return 1
t = int(input())
for i in range(t):
	n = int(input())
	ar = [int(k) for k in input().split()]
	ans = []
	mark = [0 for j in range(n)]
	ans.append(max(ar))
	mark[ar.index(max(ar))] = 1
	curgc = ans[0]
	mxgc = None
	ans1 = None
	for j in range(n - 1):
		for k in range(n):
			if mark[k] != 1:
				if mxgc == None or gcd(curgc, ar[k]) > mxgc:
					mxgc = gcd(curgc, ar[k])
					ans1 = k
		mark[ans1] = 1
		curgc = mxgc
		mxgc = None
		ans.append(ar[ans1])
	for k in ans:
		print(k, end=' ')
	print('')


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	b = [0] * n
	b[0] = arr[0]
	prev = b[0]
	vis = [False] * n
	vis[0] = True
	for i in range(1, n):
		(maxGcd, idx) = (-1, -1)
		for j in range(n):
			if vis[j]:
				continue
			curr = gcd(prev, arr[j])
			if curr > maxGcd:
				maxGcd = curr
				idx = j
		b[i] = arr[idx]
		vis[idx] = True
		prev = maxGcd
	for i in b:
		print(i, end=' ')
	print()


from math import gcd

def gt():
	return list(map(int, input().split()))
(t,) = gt()
while t:
	t -= 1
	(n,) = gt()
	ar = gt()
	vis = [0 for val in ar]
	g = max(ar)
	while 1:
		cnt = 0
		mx = 0
		for i in range(len(ar)):
			if vis[i]:
				continue
			tmp = gcd(ar[i], g)
			if tmp == g:
				print(ar[i], end=' ')
				vis[i] = 1
				cnt += 1
			if tmp < g:
				mx = max(mx, tmp)
		g = mx
		if mx == 0:
			break
	print('')


import math

def lex_Arr(a_list, n):
	temp_i = 0
	answer_arr = [0] * n
	for i in range(n):
		if a_list[i] > a_list[temp_i]:
			temp_i = i
	answer_arr[0] = a_list[temp_i]
	a_list[temp_i] = 0
	val = answer_arr[0]
	for i in range(1, n):
		a = 0
		b = 0
		for j in range(n):
			if a_list[j] and math.gcd(a_list[j], val) > b:
				b = math.gcd(a_list[j], val)
				a = j
		answer_arr[i] = a_list[a]
		val = b
		a_list[a] = 0
	return answer_arr
t = int(input())
final_arr = [[]]
for i in range(t):
	n = int(input())
	a_list = list(map(int, input().split()))
	temp_arr = lex_Arr(a_list, n)
	final_arr.append(temp_arr)
del final_arr[0]
for j in final_arr:
	print(*j)


import math
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	b.append(max(a))
	a.remove(max(a))
	gc = b[0]
	while len(a) != 0:
		c = []
		for i in a:
			c.append([i, math.gcd(i, gc)])
		c.sort(key=lambda c: c[1])
		b.append(c[-1][0])
		a.remove(c[-1][0])
		gc = math.gcd(gc, c[-1][0])
	print(*b)


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	ans = []
	ans.append(a[0])
	arr = []
	for i in range(1, n):
		arr.append((gcd(a[0], a[i]), a[i]))
	arr.sort()
	c = 1
	cgcd = a[0]
	while c < n:
		(c1, c2) = arr.pop()
		if cgcd % c1 == 0:
			ans.append(c2)
			cgcd = c1
			c += 1
			continue
		else:
			arr.append((gcd(cgcd, c1), c2))
			arr.sort()
	print(*ans)


import heapq
import collections

def gcd(a, b):
	if a < b:
		return gcd(b, a)
	if a % b == 0:
		return b
	return gcd(b, a % b)

def solve(n, arr):
	if n == 1:
		return arr
	curr_gcd = max(arr)
	ans = [curr_gcd]
	counter = collections.Counter(arr)
	counter[curr_gcd] -= 1
	for _ in range(n - 1):
		gcd_max = -1
		for num in counter:
			if counter[num] > 0:
				gcd_max = max(gcd_max, gcd(num, curr_gcd))
		next_num = -1
		for num in counter:
			if counter[num] > 0 and gcd(num, curr_gcd) == gcd_max:
				next_num = num
				break
		ans.append(next_num)
		counter[next_num] -= 1
		curr_gcd = gcd_max
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [*map(int, input().split())]
	print(' '.join(map(str, solve(n, arr))))


def gcd(a, b):
	if a == 0:
		return b
	if b == 0:
		return a
	return gcd(b, a % b)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	g = 0
	vis = [0] * n
	for i in range(n):
		(cg, mg) = (0, 0)
		index = -1
		for j in range(n):
			if vis[j]:
				continue
			cg = gcd(g, a[j])
			if cg >= mg:
				mg = cg
				index = j
		vis[index] = 1
		g = mg
		print(a[index], end=' ')
	print()


import math
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	temp = max(a)
	while len(a) > 0:
		maxi = -1
		add = -1
		for i in range(len(a)):
			if math.gcd(temp, a[i]) > maxi:
				maxi = math.gcd(temp, a[i])
				add = i
		b.append(a.pop(add))
		temp = maxi
	print(*b)


import os
import heapq
import sys, threading
import math as mt
import operator
from collections import defaultdict, deque
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 5)

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		ar = inpt()
		mx = max(ar)
		ar.sort(reverse=True)
		fr = []
		d = defaultdict(int)
		for i in range(1, n):
			d[ar[i]] += 1
		n -= 1
		ans = [(mx, mx)]
		n -= 1
		while n >= 0:
			val = ans[len(ans) - 1][1]
			mx = 0
			gcd = 0
			for i in d.keys():
				if gcd < mt.gcd(val, i):
					gcd = mt.gcd(val, i)
					mx = i
				elif gcd == mt.gcd(val, i):
					mx = max(i, mx)
			d[mx] -= 1
			if d[mx] == 0:
				d.pop(mx)
			ans.append((mx, gcd))
			n -= 1
		for i in ans:
			print(i[0], end=' ')
		print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def Proverka_numbers(x):
	list_1 = [i for i in range(1, round(x ** 0.5) + 1)]
	list_of_numbers = []
	for i in list_1:
		if x % i == 0:
			k = x // i
			list_of_numbers.append(i)
			list_of_numbers.append(k)
	list_of_numbers.sort()
	LOL = set(list_of_numbers)
	list_of_numbers = list(LOL)
	list_of_numbers.sort()
	return list_of_numbers
mass = []

def kek(mass, x):
	_kek_ = mass
	_kek_.sort()
	_kek_ = _kek_[::-1]
	for i in _kek_:
		if x % i != 0:
			del mass[mass.index(i)]
	return mass

def GCD(_dul_, x, n):
	_dul_ = kek(_dul_, x)
	return _dul_

def mass(x):
	_MUX_ = max(x)
	_del_ = Proverka_numbers(_MUX_)
	mass_b = [_MUX_]
	del x[x.index(max(x))]
	for n in range(0, len(x)):
		_max_ = 0
		for i in x:
			_kok_ = GCD(_del_[:], i, len(mass_b + [i]))
			_number_ = max(_kok_)
			if _number_ > _max_:
				max_i = i
				_max_ = _number_
				_max_mass_ = _kok_[:]
		else:
			mass_b += [max_i]
			_del_ = _max_mass_[:]
			iindex = x.index(max_i)
			del x[iindex]
	return mass_b
n = int(input())
_MASS_ = []
for i in range(n):
	K = input()
	a = input().split()
	a = list(map(int, a))
	_MASS_.append(mass(a))
for i in _MASS_:
	for j in i:
		print(j, end=' ')
	print()


from math import *
for _ in range(int(input())):
	n = int(input())
	l = sorted(list(map(int, input().split())))[::-1]
	ans = []
	vis = [False] * n
	temp = 0
	while True:
		if len(ans) == n:
			break
		idx = -1
		bst = -1
		for i in range(n):
			if vis[i] == False:
				x = gcd(l[i], temp)
				if x > bst:
					bst = x
					idx = i
		vis[idx] = True
		ans.append(l[idx])
		temp = bst
	print(*ans)


from math import gcd
t = int(input())
for i in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	used = [False for i in range(n)]
	current_gcd = 0
	B = []
	for i in range(n):
		max_new_gcd = 0
		index_achieving_max = 0
		for j in range(n):
			if not used[j]:
				val = gcd(current_gcd, A[j])
				if val > max_new_gcd:
					max_new_gcd = val
					index_achieving_max = j
		used[index_achieving_max] = True
		B.append(A[index_achieving_max])
		current_gcd = max_new_gcd
	print(' '.join(map(str, B)))


from collections import Counter
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def GCD(a, b):
	if not b:
		return a
	return GCD(b, a % b)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort(reverse=True)
	freq = Counter(arr)
	g = arr[0]
	ans = [str(g)]
	freq[arr[0]] -= 1
	if not freq[arr[0]]:
		freq.pop(arr[0])
	while len(freq):
		(g, p) = max([[GCD(g, x), x] for x in freq], key=lambda item: item[0])
		ans.append(str(p))
		freq[p] -= 1
		if not freq[p]:
			freq.pop(p)
	print(' '.join(ans))


import os
import heapq
import sys, threading
import math
import bisect
import operator
from collections import defaultdict
sys.setrecursionlimit(10 ** 5)
from io import BytesIO, IOBase

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def power(x, p, m):
	res = 1
	while p:
		if p & 1:
			res = res * x % m
		x = x * x % m
		p >>= 1
	return res

def inar():
	return [int(k) for k in input().split()]

def lcm(num1, num2):
	return num1 * num2 // gcd(num1, num2)

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = inar()
		freq = [0] * n
		res = []
		arr.sort(reverse=True)
		res.append(arr[0])
		freq[0] = 1
		gc = arr[0]
		for i in range(0, n - 1):
			mx = 0
			num = -1
			for j in range(n):
				if freq[j] != 1:
					g = gcd(gc, arr[j])
					if g > mx:
						mx = g
						num = j
			res.append(arr[num])
			freq[num] = 1
			gc = gcd(gc, arr[num])
		print(*res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin

def get_int():
	return int(stdin.readline())

def get_str():
	return stdin.readline().strip()

def get_ints():
	return map(int, stdin.readline().strip().split())

def get_array():
	return list(map(int, stdin.readline().strip().split()))

def get_array2d(row):
	return [list(map(int, stdin.readline().strip().split())) for _ in range(row)]

def gcd(num1, num2):
	while num2:
		(num1, num2) = (num2, num1 % num2)
	return num1
T = get_int()
for _ in range(T):
	N = get_int()
	A = get_array()
	st = max(A)
	A.remove(st)
	print(st, end=' ')
	(maxGcd, cnt, val) = (st, 1, 0)
	while cnt < N:
		(tGcd, val) = (0, 0)
		for a in A:
			t = gcd(maxGcd, a)
			if t >= tGcd:
				val = a
				tGcd = t
		print(val, end=' ')
		A.remove(val)
		cnt += 1
		maxGcd = tGcd
	print()


import math
for _ in range(int(input())):
	size = int(input())
	l = list(map(int, input().split()))
	ans = []
	ans.append(max(l))
	l.remove(max(l))
	k = ans[-1]
	while len(l) != 0:
		maxi = 0
		index = 0
		for i in range(len(l)):
			temp = maxi
			maxi = max(maxi, math.gcd(k, l[i]))
			if maxi != temp:
				index = l[i]
		ans.append(index)
		k = math.gcd(k, ans[-1])
		l.remove(index)
	ans = list(map(str, ans))
	ans = ' '.join(ans)
	print(ans)


def GCD(n1, n2):
	if n1 < n2:
		(n1, n2) = (n2, n1)
	while n2:
		(n1, n2) = (n2, n1 % n2)
	return n1

def highestGCD(li, taken, num):
	hgcd = 0
	pos = -1
	for i in range(len(li)):
		if not taken[i]:
			cgcd = GCD(num, li[i])
			if cgcd > hgcd:
				hgcd = cgcd
				pos = i
	if pos != -1:
		taken[pos] = True
		print(li[pos], end=' ')
		return hgcd
	else:
		return 1
for t in range(int(input())):
	n = int(input())
	li = list(map(int, input().split()))
	taken = [False] * n
	m = 0
	for i in range(1, n):
		if li[m] < li[i]:
			m = i
	print(li[m], end=' ')
	taken[m] = True
	hgcd = li[m]
	counter = 0
	while hgcd != 1 and counter < n:
		hgcd = highestGCD(li, taken, hgcd)
		counter += 1
	if counter != n:
		for i in range(n):
			if not taken[i]:
				print(li[i], end=' ')
	print()


from math import gcd

def run():
	n = int(input())
	nums = list(map(int, input().split()))
	nums.sort()
	nums.reverse()
	visited = [1] + [0] * (n - 1)
	stack = [max(nums)]
	flag = nums[0]
	for i in range(1, n):
		(p, m) = (-1, -1)
		for j in range(1, n):
			if visited[j]:
				continue
			t = gcd(flag, nums[j])
			if m == -1 or t > m:
				p = j
				m = t
		stack.append(nums[p])
		flag = m
		visited[p] = 1
	print(' '.join((str(i) for i in stack)))
T = 1
if T:
	for i in range(int(input())):
		run()
else:
	run()


import math

def get_int():
	return int(input())

def get_int_list():
	return list(map(int, input().split()))

def get_char_list():
	return list(input())

def gcd(x, y):
	if x < y:
		return gcd(y, x)
	z = x % y
	if z == 0:
		return y
	else:
		return gcd(y, z)
cases = get_int()
for _ in range(cases):
	n = get_int()
	ints = get_int_list()
	v = max(ints)
	result = [v]
	visited = set()
	visited.add(ints.index(v))
	while len(visited) < n:
		md = 0
		t = None
		for (i, d) in enumerate(ints):
			if i in visited:
				continue
			cd = gcd(v, d)
			if cd > md:
				md = cd
				t = i
		v = md
		result.append(ints[t])
		visited.add(t)
	print(*result)


import sys
input = sys.stdin.buffer.readline

def divisor(n):
	ass = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			ass.append(i)
			if i ** 2 == n:
				continue
			ass.append(n // i)
	return ass
T = int(input())
for testcase in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(a[0])
		continue
	ma = max(a)
	d = divisor(ma)
	d.sort(reverse=True)
	used = [True] * n
	b = []
	r = d[0]
	flag = True
	for e in d:
		for i in range(n):
			if used[i] and a[i] % e == 0 and (r % e == 0):
				used[i] = False
				b.append(a[i])
				r = e
	print(*b)


import sys
from math import sqrt
from collections import defaultdict
inpt = sys.stdin.readline

def inp():
	return int(inpt())

def inlist():
	return list(map(int, inpt().split()))

def instr():
	s = inpt()
	return list(s[:len(s) - 1])

def inbitstr():
	s = inpt()
	return [int(i) for i in list(s[:len(s) - 1])]

def invr():
	return map(int, inpt().split())

def printlist(a):
	for i in range(len(a)):
		print(a[i], end=' ')
	print()

class Graph:

	def __init__(self, n):
		self.n = n
		self.graph = defaultdict(list)
		self.marked = defaultdict(int)
		self.wt = defaultdict(int)

	def addEdge(self, u, v, wt):
		self.graph[u].append(v)
		self.graph[v].append(u)
		self.wt[n * u + v] = wt

	def cleanup(self):
		self.marked = defaultdict(int)

	def dfs(self, u):
		self.marked[u] = 1
		(max, maxnode) = (0, u)
		for i in self.graph[u]:
			(cur, node) = (0, 0)
			if self.marked[i] == 0:
				(cur, node) = self.dfs(i)
			if cur > max:
				max = cur
				maxnode = node
		return (1 + max, maxnode)

	def lngdfs(self, u, v):
		self.marked[u] = 1
		max = self.n
		for i in self.graph[u]:
			if i == v:
				return 1
			cur = self.n
			if self.marked[i] == 0:
				cur = self.lngdfs(i, v)
			if cur < max:
				max = cur
		return 1 + max

def gcd(x, y):
	rem = 0
	for i in range(1, min(x, y) + 1):
		if x % i == 0 and y % i == 0:
			rem = i
	return rem

def main():
	t = inp()
	for l in range(t):
		n = inp()
		a = inlist()
		a = sorted(a, reverse=True)
		curgcd = a[0]
		for i in range(n):
			curgcd = gcd(curgcd, a[i])
			for j in range(i + 2, n):
				if gcd(a[j], curgcd) > gcd(a[i + 1], curgcd):
					temp = a[i + 1]
					a[i + 1] = a[j]
					a[j] = temp
		printlist(a)
main()


from sys import stdin

def iinput():
	return int(stdin.readline())

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
from math import gcd

def nextGcd(m, a):
	mx = 0
	next = 0
	for i in range(len(a)):
		if a[i] and gcd(m, a[i]) > mx:
			mx = gcd(m, a[i])
			next = i
	return next
t = iinput()
while t:
	t -= 1
	n = iinput()
	a = linput()
	a.sort(reverse=True)
	seq = [a[0]]
	a[0] = None
	curr = seq[-1]
	while len(seq) < n:
		temp = nextGcd(curr, a)
		seq.append(a[temp])
		a[temp] = None
		curr = gcd(curr, seq[-1])
	print(*seq)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
test = int(input())
for t in range(test):
	n = int(input())
	l = list(map(int, input().split()))
	contin = 1
	for i in range(n):
		m = 1
		ind = 0
		for j in range(len(l)):
			if i == 0:
				temp = gcd(l[j], l[j])
			else:
				temp = gcd(contin, l[j])
			if temp > m:
				m = temp
				ind = j
		print(l[ind], end=' ')
		contin = m
		del l[ind]
	print()


def ans_if_list(ans):
	if isinstance(ans, str):
		return ans
	elif isinstance(ans, int):
		return ans
	else:
		return ' '.join((str(ans[i]) for i in range(len(ans))))

def input_list(typ='int'):
	if typ == 'int':
		return list(map(int, input().split()))
	elif typ == 'str':
		return list(input())
from math import gcd as motherfucker
t = int(input())
for q in range(t):
	l = int(input())
	ls = input_list()
	c = None
	if l == 1:
		ans_ls = ls
	elif l == 2:
		ans_ls = [max(ls), min(ls)]
	else:
		ans_ls = list()
		mm = max(ls)
		ans_ls.append(mm)
		ls.remove(mm)
		common = 0
		while True:
			candidate = dict()
			for i in range(len(ls)):
				if len(ans_ls) == 1:
					a = motherfucker(ans_ls[-1], ls[i])
					candidate[a] = ls[i]
				else:
					a = motherfucker(common, ls[i])
					candidate[a] = ls[i]
			common = max(candidate.keys())
			ans_ls.append(candidate[common])
			ls.remove(candidate[common])
			if len(ans_ls) == l:
				break
	print(ans_if_list(ans_ls))


from math import gcd
t = int(input())
for _ in range(t):
	n = int(input())
	a = map(int, input().split())
	a = list(a)
	a.sort(reverse=True)
	ans = [a[0]]
	d = {}
	g = a[0]
	for i in range(1, n):
		curg = 1
		pos = -1
		for j in range(1, n):
			if j not in d:
				tmp = gcd(g, a[j])
				if curg <= tmp:
					curg = tmp
					pos = j
		d[pos] = 0
		ans.append(a[pos])
		g = curg
	print(*ans)


from math import gcd
input = __import__('sys').stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = sorted(map(int, input().split()))
	ans = [s.pop()]
	cg = ans[0]
	s.reverse()
	while s:
		f = []
		ind = 0
		for i in s:
			f.append((gcd(cg, i), ind))
			ind += 1
		f.sort()
		cg = f[-1][0]
		ans += (s.pop(f[-1][1]),)
	print(*ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [0] * n
	ans[0] = max(l)
	l.remove(max(l))
	g = ans[0]
	for j in range(1, n):
		ma = 0
		for i in range(len(l)):
			if math.gcd(g, l[i]) > ma:
				ma = math.gcd(g, l[i])
				ind = l[i]
			if math.gcd(g, l[i]) == ma:
				ind = max(ind, l[i])
		g = math.gcd(g, ind)
		ans[j] = ind
		l.remove(ind)
	print(*ans)


t = int(input())

def gcd(m, n):
	x = max(m, n)
	y = min(m, n)
	r = x % y
	if r == 0:
		return y
	else:
		return gcd(r, y)

def maxgcd(x, a=[]):
	ind = 0
	maxm = 0
	for i in range(len(a)):
		g = gcd(x, a[i])
		if g >= maxm:
			maxm = g
			ind = i
	return [maxm, ind]
for i in range(t):
	a = []
	n = int(input())
	a = [int(a) for a in input().split()]
	res = []
	b = a.copy()
	g = max(b)
	res.append(max(b))
	del b[b.index(max(b))]
	while len(b) != 0:
		v = maxgcd(g, b)
		g = v[0]
		res.append(b[v[1]])
		del b[v[1]]
	v = [print(x, end=' ') for x in res]
	print('')


import sys
read = lambda : sys.stdin.readline().strip()
readi = lambda : map(int, read().split())

def gcd(b):
	a = m
	while a != b:
		if a > b:
			a = a - b
		else:
			b = b - a
	return a

def gcd1(a, b):
	while a != b:
		if a > b:
			a = a - b
		else:
			b = b - a
	return a
for _ in range(int(read())):
	n = int(read())
	nums = list(readi())
	m = max(nums)
	nums.remove(m)
	print(m, end=' ')
	prev_gcd = m
	for i in range(1, n):
		m = max(nums, key=gcd)
		nums.remove(m)
		print(m, end=' ')
		m = gcd1(m, prev_gcd)
		prev_gcd = m
		if m == 1:
			break
	print(' '.join(map(str, nums)))


import sys
import math as mt
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ind = [0] * (n + 1)
	l.sort(reverse=True)
	print(l[0], end=' ')
	g = l[0]
	ind[0] = 1
	for i in range(n - 1):
		i1 = 0
		maxi = 1
		maxval = 0
		for j in range(1, n):
			if ind[j] == 0:
				x = mt.gcd(l[j], g)
				if maxi < x:
					maxval = l[j]
					maxi = x
					i1 = j
				elif maxi == x and maxval < l[j]:
					maxi = x
					maxval = l[j]
					i1 = j
		ind[i1] = 1
		g = maxi
		print(l[i1], end=' ')
	print()


import math
t = input()
t = int(t)

def solve(n, arr):
	b1 = max(arr)
	used = set()
	ans = [0 for i in range(n)]
	ans[0] = b1
	used.add(n - 1)
	seed = b1
	for j in range(n - 1):
		max_gcd = 1
		for i in range(n):
			if i in used:
				continue
			now_gcd = math.gcd(arr[i], seed)
			if now_gcd >= max_gcd:
				max_gcd = now_gcd
				max_ind = i
		used.add(max_ind)
		seed = max_gcd
		ans[j + 1] = arr[max_ind]
	print(*ans)
for i in range(t):
	n = input()
	n = int(n)
	arr = list(map(int, input().split()))
	arr.sort()
	solve(n, arr)


def divisors(M):
	import math
	d = []
	i = 1
	while M >= i ** 2:
		if M % i == 0:
			d.append(i)
			if i ** 2 != M:
				d.append(M // i)
		i = i + 1
	d.sort()
	return d[::-1]
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	M = a[-1]
	a.pop()
	res = [M]
	used = [False] * n
	used[-1] = True
	div = divisors(M)
	G = M
	for d in div:
		if G % d != 0:
			continue
		for i in range(n - 1):
			if not used[i] and a[i] % d == 0:
				res.append(a[i])
				used[i] = True
				G = d
	print(*res)


import sys
import math
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]

def solve():
	n = int(ii())
	data = idata()
	ans = []
	mx = max(data)
	count = 0
	a = [1] * n
	while count < n:
		mx2 = 0
		for i in range(n):
			d = math.gcd(data[i], mx)
			if a[i] and mx == d:
				count += 1
				ans += [data[i]]
				a[i] = 0
			elif a[i] and mx2 < d:
				mx2 = d
		mx = mx2
	print(*ans)
	return
for t in range(int(ii())):
	solve()


import math
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = []
	b = []
	maxi = max(a)
	c.append(maxi)
	b.append(maxi)
	a[a.index(maxi)] = 0
	current = 1
	current_gcd = 0
	value = -1
	while current < n:
		for i in range(len(a)):
			if a[i] != 0:
				if math.gcd(c[current - 1], a[i]) > current_gcd:
					index = i
					value = a[i]
					current_gcd = math.gcd(c[current - 1], a[i])
		b.append(value)
		c.append(current_gcd)
		a[index] = 0
		current_gcd = 0
		value = -1
		current += 1
	for i in b:
		print(i, end=' ')
	print()


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]

def gcd(a, b):
	if b < a:
		(a, b) = (b, a)
	if a == 0:
		return b
	return gcd(b % a, a)
testCases = int(input())
answers = []
for _ in range(testCases):
	n = int(input())
	arr = input_split()
	maxi = max(arr)
	arr.remove(maxi)
	barr = [maxi]
	g = maxi
	for i in range(n - 1):
		temp = [(gcd(g, a), a) for a in arr]
		(g, to_remove) = max(temp)
		barr.append(to_remove)
		arr.remove(to_remove)
	answers.append(barr)
for a in answers:
	print(*a, sep=' ')


import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	b = [a[0]]
	j = 1
	maxi = a[0]
	for i in range(n - 1):
		m = 0
		ind = 0
		for j in range(i + 1, n):
			c = math.gcd(maxi, a[j])
			if c >= m:
				m = c
				ind = j
		if m == 1:
			b += a[i + 1:][::-1]
			break
		else:
			b += [a[ind]]
			a.pop(ind)
			a.insert(0, 0)
			maxi = m
	print(*b)


import sys
import math
input = sys.stdin.readline

def bigvova():
	n = int(input())
	nums = list(map(int, input().split()))
	used = [False for _ in range(n)]
	max_num = 0
	max_idx = 0
	for i in range(n):
		if nums[i] > max_num:
			max_num = nums[i]
			max_idx = i
	seq = [max_num]
	g = max_num
	used[max_idx] = True
	for _ in range(n - 1):
		now_gcd = 0
		now_num = 0
		now_idx = 0
		for i in range(n):
			if used[i]:
				continue
			if math.gcd(g, nums[i]) > now_gcd:
				now_gcd = math.gcd(g, nums[i])
				now_num = nums[i]
				now_idx = i
		used[now_idx] = True
		seq.append(now_num)
		g = now_gcd
	for num in seq:
		print(num, end=' ')
	print()
for _ in range(int(input())):
	bigvova()


t = int(input())
from math import gcd
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ans = []
	m = 0
	while l:
		if not ans:
			x = max(l)
			l.remove(x)
			ans.append(x)
			m = x
		else:
			c = -1
			d = 1
			for j in l:
				e = gcd(j, m)
				if e >= d:
					d = e
					c = j
			m = d
			ans.append(c)
			l.remove(c)
	print(*ans)


from sys import stdin, stdout

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
t = int(stdin.readline())
for case in range(t):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	avail = [0] * (10 ** 3 + 1)
	for item in arr:
		avail[item] += 1
	res = [max(arr)]
	avail[res[0]] -= 1
	ggcd = res[0]
	for turn in range(n - 1):
		(elem, cgcd) = (-1, 1)
		for item in arr:
			if avail[item] > 0:
				if gcd(item, ggcd) >= cgcd:
					cgcd = gcd(item, ggcd)
					elem = item
		avail[elem] -= 1
		res.append(elem)
		ggcd = cgcd
	stdout.write(' '.join(map(str, res)))
	stdout.write('\n')


def gcd(a, b):
	if a == 0:
		return b
	else:
		return gcd(b % a, a)
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	out = [str(max(arr))]
	c = max(arr)
	arr.remove(max(arr))
	while arr != []:
		max_gcd = 0
		max_value = 0
		for i in arr:
			tmp = gcd(i, c)
			if tmp > max_gcd:
				max_gcd = tmp
				max_value = i
		c = max_gcd
		out.append(str(max_value))
		arr.remove(max_value)
	print(' '.join(out))


import math
tests = int(input())
for t in range(tests):
	n = int(input())
	ls = list(map(int, input().split()))
	ls = sorted(list(ls))[::-1]
	res = [ls[0]]
	curr = ls[0]
	new_ls = []
	removed = False
	for item in ls:
		if item != curr:
			new_ls.append(item)
		elif removed:
			new_ls.append(item)
		else:
			removed = True
	ls = new_ls
	while len(ls) > 0:
		max_item = None
		max_gcd = 0
		new_ls = []
		for item in ls:
			temp = math.gcd(item, curr)
			if temp > max_gcd:
				max_item = item
				max_gcd = temp
		res.append(max_item)
		removed = False
		for item in ls:
			if item != max_item:
				new_ls.append(item)
			elif removed:
				new_ls.append(item)
			else:
				removed = True
		ls = new_ls
		curr = max_gcd
	print(' '.join(list(map(str, res))))


def GCD(a, b):
	if a == b:
		return a
	else:
		return GCD(max(a, b) - min(a, b), min(a, b))

def lexicoMax(arr):
	first = max(arr)
	arr_gcd = first
	result = [first]
	arr.remove(first)
	while len(arr) > 0:
		max_gcd = 1
		for num in arr:
			if GCD(arr_gcd, num) > max_gcd:
				max_gcd = GCD(arr_gcd, num)
				next_num = num
		if max_gcd == 1:
			return result + arr
		else:
			result.append(next_num)
			arr.remove(next_num)
			arr_gcd = max_gcd
	return result
t = int(input())
test_cases = []
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	test_cases.append((n, arr))
for case in test_cases:
	(n, arr) = case
	print(*lexicoMax(arr))


import os, sys
from io import BytesIO, IOBase
from collections import defaultdict

def main():
	from math import gcd
	for _ in range(int(input())):
		n = int(input())
		mn = 0
		a = [int(X) for X in input().split()]
		if len(a) == 1:
			print(*a)
		else:
			a.sort(reverse=True)
			mn = a[0]
			del a[0]
			c = [mn]
			i = 0
			while a:
				x = 0
				an = -1
				for j in range(n - 1 - i):
					z = gcd(mn, a[j])
					if z == mn:
						x = z
						an = j
						break
					if z > x:
						x = z
						an = j
				c.append(a[an])
				del a[an]
				mn = x
				i += 1
			print(*c)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
from math import ceil, factorial, gcd
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify
MOD = 10 ** 9 + 7
INF = float('inf')
rl = lambda : list(map(int, sys.stdin.readline().split()))
rs = lambda : sys.stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	A = rl()
	used = [False] * n
	ans = [max(A)]
	used[A.index(max(A))] = True
	g = ans[0]
	for _ in range(n - 1):
		idx = -1
		largest = -INF
		for i in range(n):
			if not used[i]:
				res = gcd(g, A[i])
				largest = max(largest, res)
				if largest == res:
					idx = i
		g = gcd(g, A[idx])
		used[idx] = True
		ans.append(A[idx])
	print(*ans)


import math
t = int(input())

def gcd(a, b):
	if a == 0:
		return b
	else:
		return gcd(b % a, a)
while t > 0:
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	b = [a[0]]
	seen = [False] * n
	seen[0] = True
	c = b[0]
	for j in range(1, n):
		max_index = 0
		max_elem = 0
		for i in range(0, n):
			ci = gcd(c, a[i])
			if not seen[i] and ci > max_elem:
				max_index = i
				max_elem = ci
		b.append(a[max_index])
		c = max_elem
		seen[max_index] = True
	print(' '.join((str(num) for num in b)))
	t -= 1


def get_factors(n):
	factors = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			factors.append(i)
			factors.append(n // i)
	factors.sort(reverse=True)
	return factors

def solve(n, a):
	Mx = 0
	for i in range(1, n):
		if a[i] > a[Mx]:
			Mx = i
	M = a.pop(Mx)
	factors = get_factors(M)
	z = 0
	l = []
	for factor in factors:
		bad_factor = False
		for el in l:
			if el % factor != 0:
				bad_factor = True
				break
		if bad_factor:
			continue
		z = 0
		while True:
			if z >= len(a):
				break
			if a[z] % factor == 0:
				l.append(a.pop(z))
			else:
				z += 1
	l.insert(0, M)
	return l

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		print(*solve(n, a))
main()


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def ans():
	n = int(input())
	a = list(map(int, input().split()))
	d = 0
	b = [0 for i in range(n)]
	vis = set()
	for i in range(n):
		maxi = 0
		ind = 0
		for j in range(n):
			if j not in vis and gcd(d, a[j]) > maxi:
				maxi = gcd(d, a[j])
				ind = j
		d = maxi
		vis.add(ind)
		b[i] = a[ind]
	print(*b)

def solve():
	for _ in range(int(input())):
		ans()
solve()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	maxx = max(arr)
	g = maxx
	ans = []
	vis = [False] * n
	while len(ans) < n:
		t = -1
		m = -1
		for i in range(n):
			if not vis[i]:
				if gcd(g, arr[i]) > m:
					t = i
					m = gcd(g, arr[i])
		ans.append(arr[t])
		vis[t] = True
		g = m
	print(*ans)


import math
t = int(input())
for i in range(t):
	(n, a) = (int(input()), list(map(int, input().split())))
	max_a = max(a)
	b = math.gcd(0, max_a)
	a.remove(max_a)
	print(b, end=' ')
	for i in range(n - 1):
		l = []
		for j in range(len(a)):
			l.append(math.gcd(b, a[j]))
		b = max(l)
		ind = l.index(b)
		nomaxgcd = a[ind]
		print(nomaxgcd, end=' ')
		a.remove(nomaxgcd)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
ORDA = 97

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return [int(i) for i in input().split()]

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def revn(n):
	return str(n)[::-1]

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=2):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base):
	new_number = 0
	while number > 0:
		new_number += number % base
		number //= base
	return new_number

def cdiv(n, k):
	return n // k + (n % k != 0)

def ispal(s):
	for i in range(len(s) // 2 + 1):
		if s[i] != s[-i - 1]:
			return False
	return True

def main():
	for _ in range(ii()):
		n = ii()
		a = li()
		b = []
		x = max(a)
		b.append(x)
		a.remove(x)
		while len(a) > 0:
			n = len(a)
			p = 0
			q = 0
			a.sort()
			for i in a:
				if math.gcd(x, i) > p:
					p = math.gcd(x, i)
					q = i
			x = p
			a.remove(q)
			b.append(q)
		print(*b)
main()


def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
for _ in range(int(input())):
	n = int(input())
	a = sorted([int(i) for i in input().split()])[::-1]
	ck = [1] * n
	ck[0] = 0
	c = [a[0]]
	cur = a[0]
	while 1:
		boo = False
		ma = 0
		p = -1
		for i in range(n):
			if ck[i]:
				g = gcd(a[i], cur)
				if g > ma:
					ma = g
					p = i
					boo = True
		if not boo:
			break
		cur = gcd(a[p], cur)
		ck[p] = 0
		c.append(a[p])
	for i in range(n):
		if ck[i]:
			c.append(a[i])
	print(*c)


def gcd_naive(a, b):
	(a, b) = (max(a, b), min(a, b))
	if b == 0:
		return a
	else:
		a_ = a % b
	return gcd_naive(b, a_)

def ans_f(a):
	b = []
	c = []
	b.append(max(a))
	c.append(b[0])
	a.remove(max(a))
	k = 0
	while len(a) > 0:
		mx = 0
		for i in a:
			if mx < gcd_naive(i, c[k]):
				mx = gcd_naive(i, c[k])
				temp = i
		k += 1
		b.append(temp)
		a.remove(temp)
		c.append(mx)
	return b
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans.append(ans_f(a))
for i in ans:
	print(*i)


def gcd(a, b):
	return a if b == 0 else gcd(b, a % b)
T = int(input())
for __ in range(T):
	n = int(input())
	nums = list(map(int, input().split()))
	cnt = {}
	for num in nums:
		cnt[num] = cnt.get(num, 0) + 1
	ret = []
	curr = None
	while cnt:
		chosen = max(cnt, key=lambda x: gcd(x, curr)) if curr else max(cnt)
		if cnt[chosen] == 1:
			cnt.pop(chosen)
		else:
			cnt[chosen] -= 1
		ret.append(chosen)
		curr = gcd(curr, chosen) if curr else chosen
	print(' '.join(map(str, ret)))


import math
T = int(input())
for _ in range(0, T):
	n = int(input())
	s = [int(x) for x in input().split()]
	s.sort()
	s = s[::-1]
	L = [s[0]]
	pos = [0] * len(s)
	pos[0] = 1
	curr = s[0]
	for i in range(1, len(s)):
		gd = 1
		ptr = 0
		for j in range(0, len(s)):
			if pos[j] == 0:
				tt = math.gcd(s[j], curr)
				if tt >= gd:
					gd = tt
					ptr = j
		L.append(s[ptr])
		pos[ptr] = 1
		curr = math.gcd(curr, s[ptr])
	print(*L)


def gcd(x, y):
	if x % y == 0:
		return y
	return gcd(y, x % y)
t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	li = [int(i) for i in l]
	l = []
	li.sort()
	li.reverse()
	done = [0 for i in range(n)]
	l.append(li[0])
	done[0] = 1
	curr = li[0]
	for j in range(1, n):
		z = 0
		for i in range(n):
			if done[i] == 1:
				continue
			p = gcd(curr, li[i])
			if p > z:
				z = p
				ans = i
		done[ans] = 1
		l.append(li[ans])
		curr = gcd(curr, li[ans])
	for i in l:
		print(i, end=' ')
	print()


def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	m = x = 0
	while l:
		(m, x) = max(((gcd(m, i), i) for i in l))
		print(x)
		l.remove(x)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase

def main():

	def solve():
		from math import inf, gcd

		def removeFromNumbersLeft(number):
			if numbersLeft[number] == 1:
				del numbersLeft[number]
			else:
				numbersLeft[number] -= 1
		n = int(input())
		numbersLeft = {}
		for num in map(lambda x: int(x), input().split()):
			if num in numbersLeft:
				numbersLeft[num] += 1
			else:
				numbersLeft[num] = 1
		b = [0] * n
		b[0] = max(numbersLeft)
		removeFromNumbersLeft(b[0])
		previousGCD = b[0]
		for i in range(1, n):
			maxGCD = -inf
			for num in numbersLeft:
				newGCD = gcd(previousGCD, num)
				if newGCD > maxGCD:
					maxGCD = newGCD
					bestNum = num
			b[i] = bestNum
			removeFromNumbersLeft(bestNum)
			previousGCD = maxGCD
		print(' '.join(map(lambda x: str(x), b)))
	t = int(input())
	for i in range(t):
		solve()
BUFFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
input = lambda : sys.stdin.readline().rstrip('\r\n')

def print(*args, **kwargs):
	sep = kwargs.pop('sep', ' ')
	file = kwargs.pop('file', sys.stdout)
	atStart = True
	for x in args:
		if not atStart:
			file.write(sep)
		file.write(str(x))
		atStart = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
main()


from math import *
from bisect import *
from collections import Counter, defaultdict, deque
I = lambda : int(input())
M = lambda : map(int, input().split())
LI = lambda : list(map(int, input().split()))
for _ in range(I()):
	n = I()
	a = LI()
	b = [0] * n
	a.sort()
	c = [a[-1]]
	b[-1] = 1
	d = 1
	g = c[0]
	while d != n:
		m = 0
		ind = -1
		for i in range(n):
			if not b[i]:
				k = gcd(g, a[i])
				if k > m:
					m = k
					ind = i
		c += [a[ind]]
		b[ind] = 1
		d += 1
		g = m
	print(*c)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	ans = []
	vis = [0] * n
	b = [0] * n
	d = 0
	for i in range(n):
		maxi = 0
		ind = 0
		for j in range(n):
			if vis[j] == 0 and math.gcd(d, x[j]) > maxi:
				maxi = math.gcd(d, x[j])
				ind = j
		d = maxi
		vis[ind] = 1
		b[i] = x[ind]
	print(*b)


import math
for vishal in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.reverse()
	lis = [a[0]]
	gc = a[0]
	del a[0]
	while len(a) > 0:
		(elem, gcans) = (-1, -1)
		for i in range(len(a)):
			if gcans < math.gcd(gc, a[i]):
				elem = i
				gcans = math.gcd(gc, a[i])
		lis.append(a[elem])
		gc = math.gcd(gc, a[elem])
		del a[elem]
	print(' '.join(map(str, lis)))


def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)
l = []
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = []
	a.sort()
	s.append(str(a[-1]))
	a = a[::-1]
	t = a[0]
	for i in range(n):
		item = 0
		gitem = 0
		for j in range(1, n - i):
			if gitem < gcd(t, a[j]):
				item = a[j]
				gitem = gcd(t, a[j])
		s.append(str(item))
		t = gcd(t, item)
		try:
			a.remove(item)
		except:
			None
	l.append(' '.join(s[:n]))
for i in l:
	print(i)


from sys import stdin, stdout
from math import gcd
for _ in ' ' * int(stdin.readline()):
	a = int(stdin.readline())
	b = list(map(int, stdin.readline().split()))
	t = 0
	z = []
	for i in range(a):
		p = 0
		k = 0
		for j in range(len(b)):
			if gcd(b[j], t) > k:
				p = j
				k = gcd(b[j], t)
		t = gcd(t, b[p])
		z.append(b.pop(p))
	print(*z)


t = int(input())
import heapq, math
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	if n == 1:
		print(A[0])
		continue
	A.sort(reverse=True)
	g = A[0]
	used = set()
	ans = []
	for i in range(n):
		M = 0
		id = -1
		for j in range(n):
			temp = math.gcd(g, A[j])
			if temp > M and j not in used:
				id = j
				M = temp
		ans.append(A[id])
		g = math.gcd(g, A[id])
		used.add(id)
	print(*ans)