You have given an array $a$ of length $n$ and an integer $x$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $q$. If $q$ is divisible by $x$, the robot adds $x$ copies of the integer $\frac{q}{x}$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $q$ is not divisible by $x$, the robot shuts down.

Please determine the sum of all values of the array at the end of the process.


-----Input-----

The first input line contains a single integer $t$ ($1 \leq t \leq 100$) — the number of test cases.

The first line of each test case contains two integers $n$ and $x$ ($1 \leq n \leq 10^5$, $2 \leq x \leq 10^9$) — the length of the array and the value which is used by the robot.

The next line contains integers $a_1$, $a_2$, ..., $a_n$ ($1 \leq a_i \leq 10^9$) — the initial values in the array.

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


-----Output-----

For each test case output one integer — the sum of all elements at the end of the process.


-----Examples-----

Input
2
1 2
12
4 2
4 6 8 2
Output
36
44


-----Note-----

In the first test case the array initially consists of a single element $[12]$, and $x=2$. After the robot processes the first element, the array becomes $[12, 6, 6]$. Then the robot processes the second element, and the array becomes $[12, 6, 6, 3, 3]$. After the robot processes the next element, the array becomes $[12, 6, 6, 3, 3, 3, 3]$, and then the robot shuts down, since it encounters an element that is not divisible by $x = 2$. The sum of the elements in the resulting array is equal to $36$.

In the second test case the array initially contains integers $[4, 6, 8, 2]$, and $x=2$. The resulting array in this case looks like $ [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1]$.

Difficulty: EASY

Solutions:
def solve(_array, y):
	sum = 0
	n = 1
	while True:
		for i in _array:
			if i % n == 0:
				sum += i
			else:
				return sum
		n = n * y
for _ in range(int(input())):
	(x, y) = list(map(int, input().split(' ')))
	_array = list(map(int, input().split(' ')))
	sum = solve(_array, y)
	print(sum)


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	(n, x) = map(int, sys.stdin.readline().split())
	A = list(map(int, sys.stdin.readline().split()))
	min_factors = None
	idx_min_factors = 0
	for (i, value) in enumerate(A):
		num_value_factors = 0
		while value % x == 0:
			num_value_factors += 1
			value //= x
		if min_factors is None or num_value_factors < min_factors:
			min_factors = num_value_factors
			idx_min_factors = i
	total = (min_factors + 1) * sum(A) + sum(A[:idx_min_factors])
	print(total)


T = int(input())

def brute_algo(n, x, a):
	new_a = a.copy()
	pos = 0
	while pos < len(new_a):
		if new_a[pos] > 0 and new_a[pos] % x == 0:
			new_a += [new_a[pos] // x] * x
			pos += 1
		else:
			break
	return sum(new_a)
for t in range(T):
	(n, x) = tuple([int(num) for num in input().split()])
	a = [int(num) for num in input().split()]

	def get_multiplicity(ai, x):
		multiplicity = 0
		while ai > 0 and ai % x == 0:
			multiplicity += 1
			ai //= x
		return multiplicity
	amult = [get_multiplicity(ai, x) for ai in a]
	min_amult = min(amult)
	norm_amult = amult.copy()
	have_found_min = False
	for i in range(len(norm_amult)):
		if have_found_min is False:
			if amult[i] > min_amult:
				norm_amult[i] = min_amult + 1
				continue
			else:
				have_found_min = True
		else:
			norm_amult[i] = min_amult
	result = sum([a[i] * (1 + norm_amult[i]) for i in range(len(a))])
	print(result)


def solve():
	(n, x) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = []
	SU = 0
	for i in a:
		now = 1
		IT = i
		while IT % x == 0:
			IT //= x
			now += 1
		b.append(now)
	mi = min(b)
	index = b.index(mi)
	for i in range(0, index + 1):
		SU += min(b[i], mi + 1) * a[i]
	for i in range(index + 1, n):
		SU += min(b[i], mi) * a[i]
	print(SU)
TTTT = int(input())
while TTTT:
	solve()
	TTTT -= 1


import sys
sys.setrecursionlimit(1000000)
from collections import defaultdict, deque, Counter
from itertools import permutations
from math import sqrt, gcd, pi, factorial
from functools import reduce
from sys import stdin
from bisect import bisect_right, bisect_left
from copy import copy

def stupid(n, x, a):
	a2 = a.copy()
	i = 0
	while i < len(a2):
		if a2[i] % x != 0:
			break
		a2 += [a2[i] // x for _ in range(x)]
		i += 1
	return sum(a2)

def calc(q, x):
	ret = 0
	while q % x == 0:
		q //= x
		ret += 1
	return ret

def solve(n, x, a):
	cnts = [calc(a[i], x) for i in range(n)]
	min_cnt = min(cnts)
	flag = True
	ret = sum(a)
	for i in range(n):
		if cnts[i] == min_cnt or not flag:
			flag = False
			ret += a[i] * min_cnt
		else:
			ret += a[i] * (min_cnt + 1)
	return ret
t = int(input())
anss = [0 for _ in range(t)]
for i in range(t):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	anss[i] = solve(n, x, a)
for ans in anss:
	print(ans)


from __future__ import division, print_function
import os
import sys
import math
from io import BytesIO, IOBase
from heapq import *
from math import factorial, floor, ceil, sqrt
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
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')

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

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

def power(x, y, p):
	y %= p - 1
	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 binary_search(arr, x):
	start = 0
	end = len(arr) - 1
	while start <= end:
		mid = (start + end) // 2
		if x == arr[mid]:
			return True
		elif x < arr[mid]:
			end = mid - 1
		else:
			start = mid + 1
	return False

def prefix_sum(arr, n):
	prev_sum = 0
	for i in range(n):
		prev_sum += arr[i]
		arr[i] = prev_sum
inf = pow(10, 20)
mod = 10 ** 9 + 7

def main():
	t = int(input())
	for _ in range(t):
		(n, x) = map(int, input().strip().split())
		arr = list(map(int, input().strip().split()))
		result = 0
		i = 0
		b = []
		for val in arr:
			b.append((val, i))
		while b[i][0] % x == 0:
			(val, freq) = b[i]
			b.append((val // x, freq + 1))
			i += 1
		freq = {}
		for (v, i) in b:
			if i not in freq:
				freq[i] = x ** i
			result += v * freq[i]
		print(result)
main()


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, x) = map(int, input().split())
		a = list(map(int, input().split()))
		ls = [(i, 1) for i in a]
		i = 0
		while ls[i][0] % x == 0:
			ls.append((ls[i][0] // x, x * ls[i][1]))
			i += 1
		ans = 0
		for i in ls:
			ans += i[0] * i[1]
		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()


def map_int_input(prompt=''):
	return map(int, input(prompt).split())

def list_int_input(prompt=''):
	return list(map(int, input(prompt).split()))

def run_prog():
	for _ in range(int(input())):
		(n, x) = map_int_input()
		l = list_int_input()
		d = [(i, 1) for i in l]
		i = 0
		s = sum(l)
		while d[i][0] % x == 0:
			d.append((d[i][0] // x, d[i][1] * x))
			s += d[i][1] * d[i][0]
			i += 1
		print(s)
try:
	run_prog()
except:
	pass


from sys import stdin
input = stdin.buffer.readline
t = int(input())
for i in range(t):
	(n, x) = map(int, input().split())
	arr = [int(x) for x in input().split()]
	dp = []
	for i in arr:
		c = 1
		while i % x == 0:
			c = c + 1
			i = i // x
		dp.append(c)
	m = min(dp)
	indx = dp.index(m)
	ans = sum(arr) * m + sum(arr[:indx])
	print(ans)


for _ in range(int(input())):
	t = 0
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = 1
	s = 0
	x = sum(b)
	flag = 0
	for i in range(1000):
		c *= a[1]
		for j in range(a[0]):
			if b[j] % c == 0:
				t += 1
			else:
				flag = 1
				break
		if flag == 1:
			break
	for i in range(t % a[0]):
		s += b[i]
	print((t // a[0] + 1) * x + s)


def get_power(num, x):
	count = 0
	while num % x == 0:
		count += 1
		num //= x
	return count

def solve(arr, x):
	smallest_power = min([get_power(num, x) for num in arr])
	res = sum(arr) * (smallest_power + 1)
	for num in arr:
		if get_power(num, x) == smallest_power:
			return res
		else:
			res += num
	return res
t = int(input())
for _ in range(t):
	(n, x) = map(int, input().split())
	arr = list(map(int, input().split()))
	print(solve(arr, x))


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	ans = 0
	l2 = []
	for i in l:
		q = int(i)
		a = 0
		while q % x == 0:
			q //= x
			a += 1
		l2.append(a)
	x = min(l2)
	found = False
	for i in range(n):
		if l2[i] == x:
			found = True
		if not found:
			ans += l[i] * (x + 2)
		else:
			ans += l[i] * (x + 1)
	print(ans)


def robot(a, x):
	s = 0
	(mini, ind) = (10 ** 5, len(a))
	for i in range(len(a)):
		j = 0
		y = a[i]
		while y % x == 0:
			y = y // x
			j += 1
		if j < mini:
			mini = j
			ind = i
	for i in range(len(a)):
		if i < ind:
			s += a[i] * (mini + 2)
		else:
			s += a[i] * (mini + 1)
	return s
res = []
for _ in range(int(input())):
	(n, x) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	res.append(robot(a, x))
print(*res, sep='\n')


def calc(a, x, d):
	if d.get(a, -1) != -1:
		return d[a]
	else:
		c = 1
		t = a
		while a % x == 0:
			c += 1
			a //= x
		d[t] = c
		return d[t]
for t in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	d = {}
	s = 0
	m = 10 ** 9
	index = 0
	for i in range(n):
		temp = calc(a[i], x, d)
		if temp < m:
			m = temp
			index = i
	for i in range(n):
		if i < index:
			s += a[i] * (m + 1)
		else:
			s += a[i] * m
	print(s)


import sys
from collections import defaultdict

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

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

def input():
	return sys.stdin.readline().strip()
from math import ceil
for _ in range(int(input())):
	(n, x) = get_ints()
	a = get_array()
	b = []
	for i in range(len(a)):
		q = a[i]
		cnt = 0
		while q % x == 0:
			q = q // x
			cnt += 1
		b.append(cnt)
	x = min(b)
	ind = -1
	for i in range(len(b)):
		if b[i] == x:
			ind = i
			break
	ans1 = 0
	for i in range(ind):
		ans1 += a[i] * (b[ind] + 2)
	for i in range(ind, n):
		ans1 += a[i] * (b[ind] + 1)
	print(ans1)


import math, sys
from collections import defaultdict, deque
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')

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

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

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

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		(n, k) = In()
		l = list(In())
		dp = [0 for x in range(n)]
		(mn, pos) = (P, -1)
		for i in range(n):
			cnt = 0
			z = l[i]
			while z % k == 0:
				cnt += 1
				z //= k
			if cnt < mn:
				mn = cnt
				pos = i
			dp[i] = cnt
		for i in range(pos, n):
			dp[i] = min(dp[i], mn)
		for i in range(pos):
			dp[i] = min(dp[i], mn + 1)
		ans = 0
		for x in range(n):
			ans += dp[x] * l[x]
			ans += l[x]
		print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


CASES = int(input())
for _ in range(CASES):
	(n, x) = map(int, input().split())
	s = list(map(int, input().split()))
	temp = 1
	ele = s[0]
	s1 = []
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			temp += 1
		else:
			s1.append((ele, temp))
			temp = 1
			ele = s[i]
	s1.append((ele, temp))
	j = 0
	while j < len(s1):
		if s1[j][0] % x == 0:
			s1.append((s1[j][0] // x, s1[j][1] * x))
		else:
			break
		j += 1
	ans = 0
	for i in s1:
		ans += i[0] * i[1]
	print(ans)


from sys import stdin
import math
t = int(stdin.readline())
for _ in range(t):
	(n, x) = map(int, stdin.readline().split())
	arr = list(map(int, stdin.readline().split()))
	mini = 10 ** 9
	ind = -1
	for i in range(n):
		tmp = arr[i]
		count = 0
		while tmp % x == 0:
			count += 1
			tmp = tmp // x
		if count < mini:
			mini = count
			ind = i
	sumi = 0
	for i in range(n):
		if i < ind:
			sumi += arr[i] * (mini + 2)
		else:
			sumi += arr[i] * (mini + 1)
	print(sumi)


from sys import stdin
input = stdin.readline

def strange_list(arr, k):
	a = []
	curr = 0
	for i in arr:
		if i != curr:
			a.append([i, 1])
			curr = i
		elif i == curr:
			a[-1][1] += 1
	i = 0
	while i < len(a) and a[i][0] % k == 0:
		a.append([a[i][0] // k, a[i][1] * k])
		i += 1
	ans = 0
	for i in a:
		ans += i[0] * i[1]
	return ans
for j in range(int(input())):
	(a, b) = map(int, input().strip().split())
	lst = list(map(int, input().strip().split()))
	print(strange_list(lst, b))


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from math import sqrt, pi, ceil, log, inf, gcd, floor
from itertools import combinations, permutations
from bisect import *
from fractions import Fraction
from heapq import *
from random import randint

def main():
	for _ in range(int(input())):
		(n, x) = map(int, input().split())
		a = deque()
		for i in input().split():
			i = int(i)
			a.append((i, 1))
		su = 0
		while a:
			z = a.popleft()
			su += z[0] * z[1]
			if not z[0] % x:
				a.append((z[0] // x, x * z[1]))
			else:
				for i in a:
					su += i[0] * i[1]
				break
		print(su)
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()


t = int(input())
while t > 0:
	t -= 1
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	brr = []
	for x in arr:
		y = x
		z = 0
		while y % k == 0:
			y //= k
			z += 1
		brr.append(z)
	mn = min(brr)
	sm = 0
	for i in range(0, n):
		if brr[i] == mn:
			break
		else:
			sm += arr[i]
	sm += (mn + 1) * sum(arr)
	print(sm)


t = int(input())
for e in range(t):
	(n, x) = input().split()
	n = int(n)
	x = int(x)
	l = input().split()
	for i in range(n):
		l[i] = int(l[i])
	l1 = l[:]
	mi = 10 ** 9
	ans = 0
	ind = 0
	for i in range(n):
		c = 0
		if mi != 10 ** 9:
			te = x ** mi
			if l1[i] % te != 0:
				while l1[i] % x == 0:
					c = c + 1
					l1[i] = l1[i] / x
				if mi > c:
					mi = c
					ind = i
		else:
			while l1[i] % x == 0:
				c = c + 1
				l1[i] = l1[i] / x
			if mi > c:
				mi = c
				ind = i
		if mi == 0:
			break
	for i in range(n):
		if i < ind:
			ans = ans + l[i] * (mi + 2)
		else:
			ans = ans + l[i] * (mi + 1)
	print(ans)


import sys
import math
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
for i in range(IN()):
	(n, x) = LI()
	a = LI()
	sm = sum(a)
	ans = 0
	ndi = 0
	co = 10 ** 9
	for i in range(n):
		ele = a[i]
		tco = 1
		while ele % x == 0:
			tco += 1
			ele /= x
		if tco < co:
			co = tco
			ndi = i
	ans += sum(a[:ndi])
	ans += sm * co
	print(ans)


def find_pow_of_x(number, x):
	result = 0
	while number % x == 0:
		result += 1
		number = number // x
	return result
task_number = int(input())
for _ in range(task_number):
	(n, x) = map(int, input().split())
	array = [int(a) for a in input().split()]
	powers = [find_pow_of_x(a, x) for a in array]
	min_index = 0
	min_power = array[0]
	for (index, p) in enumerate(powers):
		if p < min_power:
			min_power = p
			min_index = index
	whole_sum = sum(array)
	last_sum = sum(array[0:min_index])
	result = whole_sum * (min_power + 1) + last_sum
	print(result)


import sys
r = sys.stdin.readline
for _ in range(int(r())):
	(N, x) = map(int, r().split())
	L = list(map(int, r().split()))
	dp = [0] * N
	m = 9999999
	for i in range(N):
		a = L[i] + 0
		while 1:
			if a % x == 0:
				dp[i] += 1
				a = a // x
			else:
				break
		if m > dp[i]:
			m = dp[i]
	flag = 1
	ans = sum(L) * (m + 1)
	for i in range(N):
		if dp[i] > m:
			ans += L[i]
		else:
			break
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
from collections import deque
mod = 10 ** 9 + 7
md = 998244353
tc = 1
(tc,) = inp()
for _ in range(tc):
	(n, x) = inp()
	ans = 0
	a = deque([[int(i), 1] for i in input().split()])
	i = 0
	while a:
		if a[0][0] % x == 0:
			ans += a[0][0] * a[0][1]
			a.append([a[0][0] // x, a[0][1] * x])
			a.popleft()
		else:
			for j in range(len(a)):
				ans += a[j][0] * a[j][1]
			break
		i += 1
	print(ans)


import sys
import math
t = int(input().strip())
for a0 in range(t):
	l1 = [int(i) for i in input().split()]
	n = l1[0]
	x = l1[1]
	l = [int(i) for i in input().split()]
	flg = 0
	add = 0
	for i in l:
		if i % x == 0:
			continue
		else:
			flg = 1
	if flg == 1:
		flag = 0
		for i in l:
			if flag == 0 and i % x == 0:
				add += 2 * i
			else:
				add += i
				flag = 1
		print(add)
	else:
		count = 1
		a = 10 ** 10
		var = 0
		var1 = 0
		for i in range(n):
			c1 = 0
			c2 = l[i]
			while c2 % x == 0:
				c1 += 1
				c2 = c2 // x
			if c1 < a:
				a = c1
				var = i
			ans = 0
			i = 0
		while i < n:
			if i < var:
				for j in range(a + 2):
					ans += l[i]
			else:
				for j in range(a + 1):
					ans += l[i]
			i += 1
		print(ans)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	a = [(i, 1) for i in a]
	i = 0
	while a[i][0] % x == 0:
		a += [(a[i][0] // x, a[i][1] * x)]
		i += 1
	print(sum((i[0] * i[1] for i in a)))


import itertools

def solve():
	t = int(input())
	result = []
	for i in range(t):
		(n, k) = map(int, input().split())
		a = [int(i) for i in input().split()]
		group_a = []
		value = a[0]
		count = 1
		for i in range(1, len(a)):
			if a[i] == value:
				count += 1
			else:
				group_a.append((value, count))
				value = a[i]
				count = 1
		group_a.append((a[-1], count))
		a = group_a
		i = 0
		while i < len(a):
			if a[i][0] % k == 0:
				a.append((a[i][0] // k, a[i][1] * k))
			else:
				break
			i += 1
		answer = 0
		for x in a:
			answer += x[0] * x[1]
		print(answer)
solve()


tc = int(input())
for k in range(tc):
	(n, k) = list(map(int, input().split()))
	l = list(map(int, input().split()))
	div = 1
	ans = 0
	while 1:
		flag = 1
		for i in l:
			if i % div == 0:
				ans += i
			else:
				flag = 0
				break
		if flag == 0:
			break
		div = div * k
	print(ans)


def solve():
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	t = False
	s = 0
	for c in a:
		if c % x != 0:
			t = True
			break
		s += c
	if t:
		print(sum(a) + s)
		return
	wmin = 123132132
	wmini = 0
	for i in range(n):
		q = a[i]
		w = 1
		while q % x == 0:
			q = q // x
			w += 1
		if w < wmin:
			wmini = i
			wmin = w
	q = 0
	for i in range(wmini):
		q += a[i]
	print(q + sum(a) * wmin)

def main():
	test_case = int(input())
	for test in range(test_case):
		solve()
main()


from sys import stdin, stdout
from math import ceil

def ii():
	return int(stdin.readline().strip())

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

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

def mi():
	return map(int, stdin.readline().strip().split())
t = ii()
for _ in range(t):
	(n, x) = mi()
	arr = li()
	l = []
	for i in range(n):
		if len(l) == 0:
			l.append([arr[i], 1])
		elif arr[i] == l[len(l) - 1][0]:
			l[len(l) - 1][1] += 1
		else:
			l.append([arr[i], 1])
	i = 0
	while i < len(l):
		if l[i][0] % x == 0:
			if l[i][0] // x == l[len(l) - 1][0]:
				l[len(l) - 1][1] += x * l[i][1]
			else:
				l.append([l[i][0] // x, x * l[i][1]])
		else:
			break
		i += 1
	ans = 0
	for i in l:
		ans += i[0] * i[1]
	print(ans)


def findx(num, x):
	cnt = 0
	while num % x == 0:
		cnt += 1
		num //= x
	return cnt
t = int(input())
for i in range(t):
	(N, x) = map(int, input().split())
	A = list(map(int, input().strip().split()))
	d = [findx(num, x) for num in A]
	m = min(d)
	j = d.index(m)
	ans = sum(A) * (m + 1)
	ans += sum(A[:j])
	print(ans)


for t in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	y = x
	ans = sum(l)
	while 1:
		a = True
		for j in range(n):
			if l[j] % y:
				a = False
				break
			else:
				ans += l[j]
		y *= x
		if not a:
			break
	print(ans)


def nr():
	return int(input())

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

def f(x, a):
	s = 0
	u = 1
	while 1:
		for i in a:
			if i % u == 0:
				s += i
			else:
				return s
		u *= x
for _ in range(int(input())):
	(n, x) = nrs()
	print(f(x, nrs()))


import sys, os, io
from math import ceil, log
from collections import deque
t = int(input())
for _ in range(t):
	(n, x) = list(map(int, input().split()))
	l = list(map(int, input().split()))
	res = 0
	que = deque()
	for i in range(n):
		que.append([l[i], 1])
	while True:
		element = que.popleft()
		x1 = element[0]
		y = element[1]
		res = res + x1 * y
		if x1 % x == 0:
			x1 = x1 // x
			y = y * x
			que.append([x1, y])
		else:
			break
	for i in range(len(que)):
		element = que.popleft()
		a = element[0]
		b = element[1]
		res = res + a * b
	print(res)


def calc(a, x, d):
	if d.get(a, -1) != -1:
		return d
	c = 1
	t = a
	while a % x == 0:
		c += 1
		a //= x
	d[t] = c
	return d
t = int(input())
for _ in range(t):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	d = {}
	c = 0
	ind = 0
	temp = 0
	m = 10 ** 9
	flag = False
	for i in range(n):
		d = calc(a[i], x, d)
		if d[a[i]] < m:
			m = d[a[i]]
			ind = i
	for i in range(n):
		if i < ind:
			c += a[i] * (m + 1)
		else:
			c += a[i] * m
	print(c)


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
from copy import deepcopy
mod2 = 998244353

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

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

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, x) = sp()
	arr = l()
	c = [0] * n
	for i in range(n):
		temp = arr[i]
		while temp % x == 0:
			c[i] += 1
			temp //= x
	new = c[:]
	for i in range(n - 2, -1, -1):
		new[i] = min(new[i], new[i + 1])
	answer = sum(arr)
	mini = inf
	for i in range(n):
		mini = min(mini, new[i] + 1, c[i])
		answer += arr[i] * mini
	out(answer)


for _ in range(int(input())):
	(n, x) = [int(i) for i in input().split(' ')]
	a = [int(i) for i in input().split(' ')]
	m = 0
	summ = 0
	stop = 0
	while True:
		for i in a:
			if i % x ** m == 0:
				summ += i
			else:
				stop = 1
				break
		m += 1
		if stop == 1:
			break
	print(summ)


from sys import *
from math import ceil
ws = lambda : map(int, stdin.readline().strip().split())
li = lambda : list(map(int, stdin.readline().strip().split()))
mod = 1000000007

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

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

def prod(l):
	ans = 1
	for i in range(len(l)):
		ans = ans * l[i]
	return ans

def sortindex(l, a):
	c = []
	if a == -1:
		rev = True
	else:
		rev = False
	for i in range(len(l)):
		c.append([l[i], i])
	x = sorted(c, reverse=rev)
	print(x)
	c = []
	for i in range(len(l)):
		c.append(x[i][1])
	return c
for _ in range(int(input())):
	(n, x) = ws()
	lis = li()
	val = 0
	i = 0
	insider = []
	while 1:
		if i == len(lis):
			break
		elif lis[i] % x == 0:
			val += lis[i]
			num = 0
			temp = lis[i]
			while temp % x == 0:
				temp = temp / x
				num += 1
			insider.append(num)
			i += 1
		else:
			break
	while i != len(lis):
		insider.append(0)
		val += lis[i]
		i += 1
	thresh = min(insider)
	flag = 0
	for i in range(n):
		if thresh == insider[i]:
			flag = 1
		if flag == 0:
			val += (thresh + 1) * lis[i]
		else:
			val += thresh * lis[i]
	print(val)


import sys
import math

def ans(A, x):
	pivot = None
	numSplits = math.inf
	i = len(A) - 1
	while i >= 0:
		splits = 0
		curr = A[i]
		while curr % x == 0:
			splits += 1
			curr //= x
			if splits > numSplits:
				break
		if splits <= numSplits:
			pivot = i
			numSplits = splits
		i -= 1
	ans = 0
	for i in range(0, pivot):
		ans += A[i] * (numSplits + 2)
	for i in range(pivot, len(A)):
		ans += A[i] * (numSplits + 1)
	return ans

def main():
	l1 = []
	l2 = []
	for (i, line) in enumerate(sys.stdin):
		if i == 0:
			continue
		idx = i - 1
		if idx % 2 == 0:
			l1 = [int(j) for j in line.split(' ')]
		else:
			l2 = [int(j) for j in line.split(' ')]
			b = ans(l2, l1[1])
			print(b)
main()


a = int(input())
for i in range(a):
	(n, x) = tuple(map(int, input().split(' ')))
	b = list(map(lambda x: (int(x), 1), input().split(' ')))
	s = 0
	for (i, (e1, e2)) in enumerate(b):
		s += e1 * e2
		j = i
		if e1 % x == 0:
			b.append((e1 // x, e2 * x))
		else:
			break
	for (e1, e2) in b[j + 1:]:
		s += e1 * e2
	print(s)


import math

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

def getstr():
	return [str(i) for i in input().split()]

def solve():
	(n, x) = getint()
	lst = getint()
	c = 100000
	s = 0
	ind = 0
	for j in range(n):
		if j > 0 and lst[j] == lst[j - 1]:
			continue
		elif j > 1 and lst[j] == lst[j - 2]:
			continue
		k = 1
		p = lst[j]
		while True:
			if p % x == 0:
				p = p // x
				k += 1
			else:
				break
		if k < c:
			c = k
			ind = j
	for j in range(n):
		if j < ind:
			s += (c + 1) * lst[j]
		else:
			s += c * lst[j]
	print(s)
for _ in range(int(input())):
	solve()


t = int(input())
while t:
	t -= 1
	(Len, x) = [int(i) for i in input().split(' ')]
	N = [int(i) for i in input().split(' ')]
	N2 = N.copy()
	D = N.copy()
	Sum = sum(N)
	c = 1
	Index = -1
	M = True
	while M:
		c += 1
		for (index, Num) in enumerate(N):
			if Num % x == 0:
				D[index] = Num // x
			else:
				Index = index
				M = False
				break
		N = D.copy()
	del D
	del N
	if c == 1:
		Sum += sum(N2[:Index])
	else:
		Sum *= c - 1
		Sum += sum(N2[:Index])
	print(Sum)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	k = [list(l)]
	i = 0
	temp = []
	while i < n:
		if l[i] % x == 0:
			l[i] //= x
			temp.append(l[i])
		else:
			break
		i += 1
		if i == n:
			k.append(temp)
			i = 0
			temp = []
	if len(temp) != 0:
		k.append(temp)
	ans = 0
	for i in range(len(k)):
		for j in k[i]:
			ans += x ** i * j
	print(ans)


def strange_list(array, div):
	count = 0
	d = 1
	while True:
		for a in array:
			if a % d == 0:
				count += a
			else:
				return count
		d = d * div
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	element = list(map(int, input().split()))
	print(strange_list(element, x))


import math
t = int(input())
for _ in range(t):
	(n, x) = map(int, input().split())
	array = list(map(int, input().split()))
	p = []
	for e in array:
		c = 0
		while e % x == 0:
			c += 1
			e = e // x
		p.append(c)
	l = min(p)
	ans = sum(array) * (min(p) + 1)
	i = 0
	while True:
		if p[i] == min(p):
			break
		ans += array[i]
		i += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, x) = [int(z) for z in input().split()]
	a = [int(x) for x in input().split()]
	divisibilityCnts = [0 for _ in range(n)]
	for (i, z) in enumerate(a):
		cnt = 1
		while z % x == 0:
			cnt += 1
			z //= x
		divisibilityCnts[i] = cnt
	minIndex = -1
	minCnt = float('inf')
	for (i, z) in enumerate(divisibilityCnts):
		if z < minCnt:
			minCnt = z
			minIndex = i
	ans = 0
	for (i, z) in enumerate(a):
		if i < minIndex:
			ans += z * min(divisibilityCnts[i], minCnt + 1)
		else:
			ans += z * min(divisibilityCnts[i], minCnt)
	print(ans)


t = int(input())
for i in range(t):
	(n, x) = map(int, input().split())
	arr = [int(x) for x in input().split()]
	su = sum(arr)
	li = arr[:]
	i = 0
	while arr[i] % x == 0:
		arr[i] = arr[i] // x
		su += li[i]
		i = (i + 1) % n
	print(su)


t = int(input())

def solve(arr, x):
	sumx = 0
	div = x
	while True:
		for i in arr:
			if i % div == 0:
				sumx += i
			else:
				return sumx + sum(arr)
		div = div * x
	return sumx + sum(arr)
for i in range(t):
	(n, x) = map(int, input().split())
	arr = list(map(int, input().split()))
	print(solve(arr, x))


import math
import random

def nthRoot(a, x):
	count = 0
	while a > 0:
		if a % x == 0:
			a /= x
			count += 1
		else:
			break
	return count + 1
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	r = []
	idx = -1
	ma = float('inf')
	for i in range(n):
		val = nthRoot(l[i], x)
		r.append(val)
		if ma > val:
			ma = val
			idx = i
	ans = 0
	for i in range(n):
		if i <= idx:
			s = l[i] * min(r[i], ma + 1)
		else:
			s = l[i] * min(r[i], ma)
		ans += s
	print(ans)


import sys
LI = lambda : list(map(int, sys.stdin.readline().split()))
MI = lambda : map(int, sys.stdin.readline().split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline())
for _ in range(II()):
	(n, x) = MI()
	a = LI()
	cnt = {i: 1 for i in range(n)}
	i = 0
	while i < len(a):
		if a[i] % x:
			break
		cnt[len(a)] = cnt[i] * x
		a.append(a[i] // x)
		i += 1
	ans = 0
	for (i, v) in enumerate(a):
		ans += v * cnt[i]
	print(ans)


import math

def ct(elem, x):
	count = 0
	while elem > 0:
		if elem % x:
			break
		count += 1
		elem //= x
	return count
for i in range(0, int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	sum_ = sum(a)
	my_list = list([0 for j in range(0, len(a))])
	for j in range(0, len(a)):
		my_list[j] = ct(a[j], x)
	min_ = min(my_list)
	my_sum = sum_ * (min_ + 1)
	sum_ = sum(a[0:my_list.index(min_)])
	print(my_sum + sum_)


def strange_list(arr, n, x):
	S = 0
	minK = mk(arr[0], x)
	minKInd = 0
	for i in range(n):
		k = mk(arr[i], x)
		if k < minK:
			minK = k
			minKInd = i
	for i in range(n):
		qmk = minK + 1 if i < minKInd else minK
		S += arr[i] * (qmk + 1)
	return S

def mk(q, x):
	k = 0
	while q % x == 0:
		k += 1
		q = q / x
	return k
t = int(input())
for i in range(t):
	inps = input().split(' ')
	n = int(inps[0])
	x = int(inps[1])
	arr = list(map(lambda x: int(x), input().split(' ')))
	print('{0}'.format(int(strange_list(arr, n, x))))


def delet(n, x):
	global dp, limit
	orig_n = n
	i = 0
	while n % x == 0 and (limit is None or i < limit):
		n //= x
		if len(dp) - 1 >= i:
			dp[i] += orig_n
		else:
			dp.append(orig_n)
		i += 1
	return i
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	i = 0
	limit = None
	dp = []
	lp = 0
	ans = 0
	while i < len(a):
		ans += a[i]
		k = delet(a[i], x)
		if limit is None or limit > k:
			limit = k
		i += 1
	ans += sum(dp[:limit + 1])
	print(ans)


T = int(input())
for __ in range(T):
	(N, X) = map(int, input().split())
	listi = list(map(int, input().split()))
	alt = []
	i = 0
	for x in listi:
		if x % X == 0:
			listi.append(x // X)
		else:
			break
	lent = len(listi)
	for _ in range(lent):
		i += pow(X, _ // N) * listi[_]
	print(i)


def check(i):
	c = 0
	p = 1
	while i % x == 0:
		c += 1
		i = i // x
	return c + 1
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = []
	a = list(map(int, input().split()))
	an = 0
	m = 1000000009
	b = [0] * n
	for i in range(n):
		b[i] = check(a[i])
		if b[i] < m:
			ind = i
			m = b[i]
	for i in range(n):
		if i < ind:
			an += a[i] * min(b[i], m + 1)
		elif i == ind:
			an += a[i] * m
		else:
			an += a[i] * min(b[i], m)
	print(an)


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

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

def v(a, x):
	p = 0
	while a % x == 0:
		a //= x
		p += 1
	return p

def solve():
	(n, x) = rl()
	A = rl()
	ans = sum(A)
	i = 0
	p = 1
	while 1:
		if A[i] % x == 0:
			ans += A[i] * p
			A[i] //= x
		else:
			break
		if i < len(A) - 1:
			i += 1
		else:
			i = 0
			p *= x
	print(ans)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


for t in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	s = sum(l)
	c = 0
	u = x
	while c == 0:
		for i in l:
			if i % u == 0:
				s = s + i
			else:
				c = c + 1
				print(s)
				break
		u = u * x


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	arr = list(map(int, input().split()))
	res = 0
	tmp = arr.copy()
	new_arr = [0] * n
	for i in range(n):
		cnt = 0
		while arr[i] % x == 0:
			cnt += 1
			arr[i] = arr[i] // x
		new_arr[i] = cnt
	idx = new_arr.index(min(new_arr))
	min_value = min(new_arr)
	res = (min_value + 1) * sum(tmp) + sum(tmp[:idx])
	print(res)


t = int(input())

def nums(n, k):
	ct = 1
	while n % k == 0:
		n /= k
		ct += 1
	return ct

def robot(n, x, l):
	mn = 0
	divs = list()
	total = 0
	for i in range(n):
		divs.append(nums(l[i], x))
		if divs[i] < divs[mn]:
			mn = i
	for i in range(n):
		if i < mn:
			total += l[i] * (divs[mn] + 1)
		else:
			total += l[i] * divs[mn]
	print(total)
	return
for _ in range(t):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	robot(n, x, l)


t = int(input())
for _ in range(t):
	(n, x) = map(int, input().split())
	A = list(map(int, input().split()))
	B = [0] * n
	flag = 1
	for i in range(n):
		temp = A[i]
		while temp % x == 0:
			temp = temp // x
			B[i] += 1
	cut = min(B)
	ans = sum(A)
	for i in range(n):
		if flag == 1:
			ans += A[i] * min(cut + 1, B[i])
			if cut == B[i]:
				flag = 0
		else:
			ans += A[i] * min(B[i], cut)
	print(ans)


t = int(input())
for _ in range(t):
	(n, x) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	(m, ind) = (10 ** 9, 0)
	for i in range(n):
		if a[i] % x != 0:
			ind = i
			m = 0
			break
		else:
			c = 0
			t = a[i]
			while t % x == 0:
				t = t // x
				c = c + 1
			if c < m:
				m = c
				ind = i
	m = m + 1
	ans = 0
	for i in range(n):
		if i < ind:
			ans = ans + a[i] * (m + 1)
		else:
			ans = ans + a[i] * m
	print(ans)


for t in range(int(input())):
	(n, x) = map(int, input().split())
	arr = [int(x) for x in input().split()]
	ans = sum(arr)
	h = []
	index = -1
	minm = 999999999
	for i in range(n):
		cnt = 0
		temp = arr[i]
		while temp % x == 0:
			temp = temp // x
			cnt += 1
		h.append(cnt)
		if minm > cnt:
			minm = cnt
			index = i
	ans += ans * minm
	for i in range(index):
		ans += arr[i]
	print(ans)


def divisibility(n, x):
	c = 0
	while n % x == 0:
		c += 1
		n = n / x
	return c

def solve():
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	mindiv = 999
	mindivi = 0
	for i in range(n):
		div = divisibility(a[i], x)
		if div < mindiv:
			mindiv = div
			mindivi = i
	sum = 0
	for i in range(n):
		if i < mindivi:
			sum += a[i] * (mindiv + 2)
		else:
			sum += a[i] * (mindiv + 1)
	print(sum)
t = int(input())
for _ in range(t):
	solve()


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')
t = int(input())
while t > 0:
	t -= 1
	(n, x) = [int(x) for x in input().split()]
	arr = [int(x) for x in input().split()]
	count = [0 for x in range(n)]
	for i in range(n):
		val = arr[i]
		c = 1
		while True:
			if val % x == 0:
				val = val // x
				c += 1
			else:
				count[i] = c
				break
	s = sum(arr)
	index = 0
	val = count[0]
	for i in range(1, n):
		if count[i] < val:
			index = i
			val = count[i]
	total = s * val
	for i in range(index):
		total += arr[i]
	print(total)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	odd_appear = []
	for i in a:
		cnt = 0
		while i % x == 0:
			cnt += 1
			i = i // x
		odd_appear.append(cnt)
	m = min(odd_appear)
	i = odd_appear.index(m)
	print((m + 2) * sum(a[:i]) + (m + 1) * sum(a[i:]))


import sys
import math
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
for i in range(IN()):
	(n, x) = LI()
	a = LI()
	sm = sum(a)
	ans = 0
	ndi = 0
	co = 10 ** 9
	for i in range(n):
		if i > 0 and a[i] == a[i - 1]:
			continue
		for j in range(1, co + 1):
			if a[i] % x ** j != 0:
				if j < co:
					co = j
					ndi = i
					break
	ans += sum(a[:ndi])
	ans += sm * co
	print(ans)


t = int(input())
for j in range(t):
	(n, x) = input().split()
	n = int(n)
	x = int(x)
	lst = [int(i) for i in input().split()]
	Sum = sum(lst)
	mc = 10 ** 9
	index = 0
	for i in range(n):
		c1 = 0
		a = lst[i]
		if i == 0 or a % x ** mc != 0:
			while a % x == 0:
				c1 = c1 + 1
				a = a / x
			if c1 < mc:
				mc = c1
				index = i
		if mc == 0:
			break
	ans = Sum * (mc + 1)
	for i in range(n):
		if i != index:
			ans = ans + lst[i]
		else:
			break
	print(ans)


for _ in range(int(input())):
	a = input().split()
	n = int(a[0])
	x = int(a[1])
	A = list(map(int, input().split()))
	sum1 = 0
	B = [0] * n
	for i in range(n):
		s = A[i]
		e = 0
		while True:
			if s % x == 0:
				s = s // x
				e += 1
			else:
				break
		B[i] = e
	min1 = min(B)
	index = B.index(min(B))
	sum1 = sum(A[:index])
	print(sum(A) * (min1 + 1) + sum1)


t = int(input())
for _ in range(t):
	[n, x] = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	minimum = 30
	nomer = 0
	for i in range(n):
		k = 0
		tmp = a[i]
		while tmp % x == 0:
			k += 1
			tmp //= x
		if k < minimum:
			minimum = k
			nomer = i
	print(sum(a) * (minimum + 1) + sum(a[:nomer]))


import sys
input = sys.stdin.readline
import math
import copy
import collections
from collections import deque
inf = 10 ** 18
for _ in range(int(input())):
	(n, x) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	ans = 0
	stop = [inf, inf]
	for i in range(n):
		val = arr[i]
		num = 1
		while val % x == 0:
			num += 1
			val //= x
		if num < stop[1]:
			stop = [i, num]
	for i in range(n):
		if i < stop[0]:
			ans += arr[i] * (stop[1] + 1)
		else:
			ans += arr[i] * stop[1]
	print(ans)


from math import ceil

def LargestDiv(n, x):
	div_pow = 0
	curr = x ** div_pow
	while n % curr == 0:
		div_pow += 1
		curr *= x
	return div_pow - 1

def SmallestPow(a, x):
	smallest = 10000000000.0
	sm_ind = -1
	for i in range(len(a)):
		temp = LargestDiv(a[i], x)
		if smallest > temp:
			smallest = temp
			sm_ind = i
	return [sm_ind, smallest]
t = int(input())
for j in range(t):
	ff = list(input().split())
	n = int(ff[0])
	x = int(ff[1])
	aa = list(map(int, input().split()))
	imp_dat = SmallestPow(aa, x)
	ans = 0
	for i in range(n):
		if i < imp_dat[0]:
			ans += aa[i] * (imp_dat[1] + 2)
		else:
			ans += aa[i] * (imp_dat[1] + 1)
	print(ans)


t = int(input())
for _ in range(t):
	l = list(map(int, input().split()))
	(n, x) = (l[0], l[1])
	l = list(map(int, input().split()))
	arr = []
	for i in range(n):
		k = 0
		p = l[i]
		while p % x == 0:
			k += 1
			p = p // x
		arr.append(k)
	b = min(arr)
	f = arr.index(min(arr))
	s = 0
	for i in range(n):
		if i <= f:
			d = l[i]
			su = l[i]
			k = 0
			while d % x == 0 and k < b + 1:
				d = d // x
				su += l[i]
				k += 1
		else:
			d = l[i]
			su = l[i]
			k = 0
			while d % x == 0 and k < b:
				d = d // x
				su += l[i]
				k += 1
		s += su
	print(s)


def cal(a, x):
	(v, u) = (0, 1)
	while 1:
		for i in a:
			if i % u == 0:
				v += i
			else:
				return v
		u *= x
for v in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	print(cal(a, x))


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	A = list(map(int, input().split()))
	B = A.copy()
	s = sum(A)
	i = 0
	while i < len(B) and B[i] % x == 0:
		A.append(A[i])
		s += A[i]
		B.append(B[i] // x)
		i += 1
	print(s)


ans = []

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

def readline():
	return list(map(int, input().split()))
x_test = 1
if x_test == 0:
	x_test = 1
else:
	x_test = int(input())
for _ in range(x_test):
	(n, x) = readline()
	a = readline()
	result = 0
	k = 0
	end = False
	while True:
		temp = []
		for i in a:
			result += i * pow(x, k)
			if i % x == 0 and (not end):
				temp.append(i // x)
			else:
				end = True
		k += 1
		if end:
			for i in temp:
				result += i * pow(x, k)
			break
		else:
			a = temp
	ans.append(result)
ans = str(ans)
lls = len(ans)
_ans = ans[1:lls - 1].replace(', ', '\n')
print(_ans)


def mindex(arr):
	m = arr[0]
	dex = 0
	for (i, v) in enumerate(arr):
		if v < m:
			m = v
			dex = i
	return (m, dex)

def findpow(n, x):
	t = 0
	while n % x == 0:
		n //= x
		t += 1
	return t

def solve(arr, x):
	pows = [findpow(i, x) for i in arr]
	(m, dex) = mindex(pows)
	return (m + 2) * sum(arr[:dex]) + (m + 1) * sum(arr[dex:])
t = int(input())
ans = []
for i in range(t):
	(n, x) = map(int, input().split())
	arr = [int(i) for i in input().split()]
	ans.append(solve(arr, x))
for i in ans:
	print(i)


import os
from math import *

def debugprint(arg):
	if os.path.isfile('debug.txt'):
		print(arg)

def divisible(n, x):
	c = 0
	while n % x == 0:
		c += 1
		n = n // x
	return c

def pb2():
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	i = 0
	s = 0
	lp = [divisible(i, x) for i in l]
	mini = min(lp)
	mini_index = lp.index(mini)
	s = 0
	for i in range(n):
		if i < mini_index:
			s += (mini + 2) * l[i]
		else:
			s += (mini + 1) * l[i]
	print(s)

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


import sys
sys.setrecursionlimit(2000)
from collections import Counter
from functools import reduce
from heapq import heappush, heappop

def timesDivisible(num, x):
	c = 0
	while num % x == 0:
		num = num // x
		c += 1
	return c
t = [int(val) for val in sys.stdin.readline().split()][0]
for test in range(t):
	(n, x) = [int(val) for val in sys.stdin.readline().split()]
	a = [int(val) for val in sys.stdin.readline().split()]
	divs = [(val, timesDivisible(val, x)) for val in a]
	min_divs = min(divs)
	min_divs = float('inf')
	for (val, d) in divs:
		min_divs = min(min_divs, d)
	summ = 0
	found = False
	for (val, d) in divs:
		if d == min_divs:
			found = True
		if found:
			summ += val * (min_divs + 1)
		else:
			summ += val * (min_divs + 2)
	print(summ)


temp = int(input())
for eqw in range(temp):
	(n, x) = list(map(int, input().split(' ')))
	li = list(map(int, input().split(' ')))
	temp = []
	low = pow(10, 10)
	for i in li:
		t = 1
		while True:
			if i % pow(x, t) == 0:
				t += 1
			else:
				break
		temp.append(t)
		low = min(low, t)
	ans = 0
	i = 0
	while i < n:
		if temp[i] == low:
			break
		ans += (low + 1) * li[i]
		i += 1
	while i < n:
		ans += low * li[i]
		i += 1
	print(ans)


def madegree(q, x):
	count = 0
	while True:
		if q % x == 0:
			q = q / x
			count = count + 1
		else:
			break
	return count
t = int(input())
for _ in range(t):
	(n, x) = input().split()
	n = int(n)
	x = int(x)
	arr = list(map(int, input().split()))
	su = 0
	ind = 0
	maaa = 10 ** 9
	for i in range(n):
		if maaa > madegree(arr[i], x):
			maaa = madegree(arr[i], x)
			ind = i
	su = su + (maaa + 2) * sum(arr[:ind])
	su = su + (maaa + 1) * sum(arr[ind:])
	print(su)


import sys
pin = sys.stdin.readline

def numOfDev(a):
	num = 1
	while a % X == 0:
		a = a // X
		num += 1
	return num
for T in range(int(pin())):
	(N, X) = map(int, pin().split())
	A = [*map(int, pin().split())]
	M = [*map(numOfDev, A)]
	mn = min(M)
	mi = M.index(mn)
	sm = 0
	for i in range(N):
		if i < mi:
			sm += A[i] * (mn + 1)
		else:
			sm += A[i] * mn
	print(sm)


test_cases = int(input())
res = []
for test in range(test_cases):
	st = input()
	ls = st.split()
	n = int(ls[0])
	x = int(ls[1])
	st = input()
	ls = st.split()
	arr = []
	varr = []
	sm = 0
	coun = 1
	for i in range(len(ls)):
		value = int(ls[i])
		if i < len(ls) - 1:
			if ls[i] != ls[i + 1]:
				arr.append(value)
				varr.append(coun)
				coun = 1
			else:
				coun += 1
		else:
			arr.append(value)
			varr.append(coun)
	i = 0
	while i < len(arr):
		if arr[i] % x != 0:
			break
		sm += arr[i] * varr[i]
		arr.append(arr[i] // x)
		varr.append(varr[i] * x)
		i += 1
	while i < len(arr):
		sm += arr[i] * varr[i]
		i += 1
	res.append(sm)
for value in res:
	print(value)


from sys import stdin, stdout
input = stdin.readline
from collections import defaultdict as dd
from collections import deque
import math

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

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

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

def getls():
	return list(map(str, input().strip().split()))

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

def geta():
	return int(input())

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

def solve():
	for i in range(geta()):
		(n, x) = geti()
		a = getl()
		now = 0
		q = []
		for i in a:
			q.append((i, 1))
		ans = 0
		ok = True
		i = 0
		while i < len(q):
			(val, num) = q[i]
			ans += val * num
			i += 1
			if val % x == 0 and ok:
				q.append((val // x, num * x))
			else:
				ok = False
				break
		for j in range(i, len(q)):
			(val, num) = q[j]
			ans += val * num
		print(ans)
solve()


def max_grade(elem, x):
	grade = 0
	while elem % x == 0:
		elem //= x
		grade += 1
	return grade

def solve(n, x, s):
	summa = sum(s)
	results = []
	grade = 0
	min_grade = 1000000000000
	save_i = 0
	for i in range(n):
		grade = max_grade(s[i], x)
		results.append(grade)
		if grade < min_grade:
			min_grade = grade
			save_i = i
	summa += min_grade * summa
	summa += sum(s[0:save_i])
	print(summa)
for i in range(int(input())):
	(n, m) = map(int, input().split())
	s = list(map(int, input().split()))
	solve(n, m, s)


import math
t = int(input())
for i in range(t):
	(n, x) = map(int, input().strip().split(' '))
	lst = list(map(int, input().strip().split(' ')))
	c = 100000
	s = 0
	ind = 0
	for j in range(n):
		if j > 0 and lst[j] == lst[j - 1]:
			continue
		elif j > 1 and lst[j] == lst[j - 2]:
			continue
		k = 1
		p = lst[j]
		while True:
			if p % x == 0:
				p = p // x
				k += 1
			else:
				break
		if k < c:
			c = k
			ind = j
	for j in range(n):
		if j < ind:
			s += (c + 1) * lst[j]
		else:
			s += c * lst[j]
	print(s)


t = int(input())
for _ in range(t):
	(n, x) = tuple(map(int, input().split()))
	arr = list(map(int, input().split()))
	sum_of_arr = sum(arr)
	how_many_x = []
	min_x = 0
	for i in range(n):
		count = 0
		temp = arr[i]
		while temp % x == 0:
			count += 1
			temp //= x
		how_many_x.append(count)
		min_x = i if count < how_many_x[min_x] else min_x
	part_one = sum(arr[:min_x])
	print((how_many_x[min_x] + 1) * sum_of_arr + part_one)


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 fi():
	return float(input())

def si():
	return input()

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

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

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

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

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

def lcm(x, y):
	return x * y // gcd(x, y)
mod = 1000000007

def modInverse(b, m):
	g = gcd(b, m)
	if g != 1:
		return -1
	else:
		return pow(b, m - 2, m)

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

def modu(a, b, m):
	a = a % m
	inv = modInverse(b, m)
	if inv == -1:
		return -999999999
	else:
		return inv * a % m
from math import log, factorial, cos, tan, sin, radians, floor, log2
import bisect
from decimal import *
getcontext().prec = 50
abc = 'abcdefghijklmnopqrstuvwxyz'
pi = 3.141592653589793

def gcd1(a):
	if len(a) == 1:
		return a[0]
	ans = a[0]
	for i in range(1, len(a)):
		ans = gcd(ans, a[i])
	return ans

def mykey(x):
	return (x[0], -x[1])

def main():
	for _ in range(ii()):
		(n, x) = mi()
		a = li()
		b = []
		b.extend(a)
		s = sum(a)
		l = []
		for i in range(n):
			c = 0
			while a[i] % x == 0:
				c += 1
				a[i] //= x
			l.append(c)
		ans = 0
		y = min(l)
		ind = -1
		for i in range(n):
			if l[i] == y:
				ind = i
				break
		ans = s * (y + 1)
		for i in range(ind):
			ans += b[i]
		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')

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()


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	element = list(map(int, input().split()))
	count = 0
	d = 1
	flag = True
	while flag:
		for a in element:
			if a % d == 0:
				count += a
			else:
				flag = False
				break
		d = d * x
	print(count)


t = int(input())
for i in range(t):
	k = input()
	(n, x) = [int(it) for it in k.split(' ')]
	a = input()
	a = [int(it) for it in a.split(' ')]
	mn = float('inf')
	c = 0
	idx = -1
	min_idx = idx
	min_v = 0
	for it in a[:]:
		idx += 1
		c = 0
		if it % x ** mn == 0:
			continue
		else:
			while it % x == 0:
				it = it // x
				c += 1
				if c >= mn:
					break
			if c < mn:
				mn = c
				min_idx = idx
	sm = 0
	sm += sum(a) * (mn + 1)
	for j in range(min_idx):
		sm += a[j]
	print(sm)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	Q = list(map(int, input().split()))
	ans = 0
	down = False
	w = 1
	while not down:
		for i in range(n):
			if Q[i] is None:
				down = True
				break
			ans += w * Q[i]
			if Q[i] % x == 0:
				Q[i] //= x
			else:
				Q[i] = None
				pass
		w *= x
	print(int(ans))


import sys, collections, math, itertools, random, bisect
INF = sys.maxsize

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

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

def input():
	return sys.stdin.readline().strip()
mod = 1000000007

def append_main(val, num, n, x, q):
	if len(q) and q[-1][0] == val:
		num += q[-1][1]
		q.pop()
	q.append([val, num])
	return

def solve(n, x, q):
	arr = get_array()
	for i in arr:
		append_main(i, 1, n, x, q)
	s = 0
	while len(q):
		(val, num) = (q[0][0], q[0][1])
		s += val * num
		q.popleft()
		if val % x:
			break
		append_main(val // x, x * num, n, x, q)
	while len(q):
		(val, num) = (q[0][0], q[0][1])
		s += val * num
		q.popleft()
	print(s)
for _ in range(int(input())):
	(n, x) = get_ints()
	q = collections.deque()
	solve(n, x, q)


def solve(arr, x):
	n = len(arr)
	min_mod = float('inf')
	j = n
	for i in range(n):
		temp = arr[i]
		mod = 0
		while temp % x == 0:
			mod += 1
			temp //= x
		if mod < min_mod:
			min_mod = mod
			j = i
	ans = 0
	for i in range(n):
		if i < j:
			ans += (min_mod + 1) * arr[i]
			ans += arr[i]
		else:
			ans += (min_mod + 1) * arr[i]
	return ans
t = int(input())
while t:
	t -= 1
	(n, x) = map(int, input().split())
	arr = list(map(int, input().split()))
	print(solve(arr, x))


def strangeList(a, x):
	i = 0
	n = len(a)
	count = 0
	flag = 0
	while True:
		j = 0
		while j < n:
			if a[j] % x ** i == 0:
				count += a[j]
			else:
				return count
			j += 1
		i += 1
	return count
t = int(input())
for i in range(t):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	print(strangeList(a, x))


def main():
	for num in range(int(input())):
		(n, x) = map(int, input().split())
		a = list(map(int, input().split()))
		(mi, mii) = (100000, None)
		for i in range(n):
			v = a[i]
			t = 1
			while v % x == 0:
				t += 1
				v //= x
			if t < mi:
				mi = t
				mii = i
		print(sum(a) * mi + sum(a[:mii]))
main()


t = int(input())

def order(so, x):
	ans = 1
	while so % x == 0:
		so = so // x
		ans += 1
	return ans
for _ in range(t):
	(n, x) = map(int, input().split())
	minn = 30
	tongcut = 0
	total = 0
	for num in map(int, input().split()):
		if order(num, x) < minn:
			tongcut = num
			total += num
			minn = order(num, x)
		else:
			tongcut += num
			total += num
	print((minn + 1) * total - tongcut)


import sys

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
from collections import defaultdict, Counter
for _ in range(ri()):
	(n, x) = ria()
	l = ria()
	z = 0
	a = 0
	y = 1
	flag = 0
	j = n
	while 1:
		for i in range(n):
			if l[i] % x == 0:
				a = a + y * l[i]
				l[i] = l[i] // x
			else:
				flag = 1
				j = min(j, i)
				a = a + y * l[i]
		y *= x
		if flag:
			break
	for i in range(j):
		a = a + y * l[i]
	print(a)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	for i in a:
		if i % x == 0:
			a.append(i // x)
		else:
			break
	s = 0
	for i in range(len(a)):
		s += a[i % n]
	print(s)


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

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

def output(answer):
	stdout.write(str(answer))
num = int(z())
for _ in range(num):
	(n, x) = zzz()
	arr = zzz()
	total = sum(arr)
	lst = [0] * n
	for (j, i) in enumerate(arr):
		if i % x == 0:
			while i % x == 0:
				i = i // x
				lst[j] += 1
		else:
			break
	mi = min(lst)
	j = lst.index(mi)
	print(total + mi * total + sum(arr[:j]))


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	s = 0
	l = []
	for i in range(n):
		c = 0
		k = a[i]
		while k % x == 0:
			c += 1
			k = k // x
		l.append(c)
	m = min(l)
	idx = l.index(m)
	for i in range(idx):
		l[i] = m + 1
	for i in range(idx, n):
		l[i] = m
	for i in range(n):
		s += a[i] * (l[i] + 1)
	print(s)


for t in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = [1] * n
	sup = 0
	xx = 0
	kek = 999999
	for i in range(n):
		xx += a[i]
		y = a[i]
		while y % (x * x * x * x) == 0:
			ans[i] += 4
			y //= x * x * x * x
		while y % x == 0:
			ans[i] += 1
			y //= x
		if ans[i] < kek:
			kek = ans[i]
	for i in range(n):
		if ans[i] == kek:
			break
		else:
			sup += a[i]
	print(xx * kek + sup)


for _ in range(int(input())):
	(n, x) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = []
	for i in a:
		b.append(i)
	s = sum(a)
	q = 0
	while q == 0:
		for i in range(n):
			if a[i] % x == 0:
				s += b[i]
				a[i] = a[i] // x
			else:
				q = 1
				break
	print(s)


from collections import defaultdict
import sys

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

def ls():
	return list(map(int, list(input())))

def la():
	return list(input())

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

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = ii()
for i in range(t):
	(n, x) = li()
	a = li()
	b = []
	for e in a:
		count = 0
		while e % x == 0:
			e = e // x
			count += 1
		b.append(count)
	minm = min(b)
	ans = sum(a) * (minm + 1)
	ans += sum(a[0:b.index(minm)])
	print(ans)


def solve(a, x):
	ans = 0
	u = 1
	while True:
		for i in a:
			if i % u == 0:
				ans += i
			else:
				return ans
		u *= x
	return ans
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	print(solve(a, x))


def min_mum(number, x, mn):
	i = 0
	while number % x == 0:
		number /= x
		i += 1
		if i >= mn:
			return mn
	return i
t = int(input())
for _ in range(t):
	tab = [0, 10 ** 10]
	(n, x) = [int(i) for i in input().split()]
	s = 0
	arr = [int(i) for i in input().split()]
	for i in range(n):
		res = min_mum(arr[i], x, tab[1])
		if res < tab[1]:
			tab[1] = res
			tab[0] = i
	s = 0
	for i in range(n):
		if i < tab[0]:
			s += arr[i] * (tab[1] + 2)
		else:
			s += arr[i] * (tab[1] + 1)
	print(s)


def strangeList(n, k, array):
	factorList = [0] * n
	min_factor_index = 0
	for x in range(n):
		p = array[x]
		while p % k == 0:
			factorList[x] += 1
			p = p / k
	min_index = 0
	min_factor = factorList[min_index]
	for x in range(n):
		if factorList[x] < min_factor:
			min_factor_index = x
			min_factor = factorList[min_factor_index]
	ans = 0
	for x in range(n):
		if x < min_factor_index:
			ans += array[x] * (min_factor + 2)
		else:
			ans += array[x] * (min_factor + 1)
	return ans
t = int(input())
final = []
for _ in range(t):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	final.append(strangeList(n, x, l))
for _ in range(t):
	print(final[_])


cases = int(input())
for _ in range(cases):
	(n, div) = map(int, input().split())
	l = list(map(int, input().split()))
	count = [1] * len(l)
	totalSum = 0
	for i in range(n):
		val = l[i]
		iterations = 1
		while val % div == 0:
			val //= div
			iterations += 1
		count[i] = iterations
	minCount = min(count)
	passed = False
	for i in range(n):
		if count[i] == minCount:
			passed = True
		totalSum += minCount * l[i]
		if not passed:
			totalSum += l[i]
	print(totalSum)


def solve(b, c):
	(ans, cn) = (0, 1)
	while True:
		for i in c:
			if i % cn == 0:
				ans += i
			else:
				return ans
		cn *= b
	return ans
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	c = list(map(int, input().split()))
	print(solve(b, c))


import math
from sys import stdin
mx = math.inf
mn = -math.inf

def i():
	return int(stdin.readline().strip())

def f():
	return float(stdin.readline().strip())

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

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

def arf():
	return list(map(float, stdin.readline().split()))

def ars():
	return list(map(str, stdin.readline().split()))

def counter(n, x):
	cnt = 0
	while n % x == 0:
		cnt += 1
		n = n / x
	return cnt

def main():
	(n, x) = ari()
	arr = ari()
	vec = [0] * n
	for i in range(n):
		vec[i] = counter(arr[i], x)
	arr_min = mx
	ix = 0
	for i in range(n):
		if vec[i] < arr_min:
			ix = i
			arr_min = vec[i]
	sum = 0
	for i in range(n):
		cnt = arr_min
		if i < ix:
			cnt += 1
		sum += arr[i] * (cnt + 1)
	print(sum)
t = 1
t = i()
for _ in range(t):
	main()


for _ in range(int(input())):
	(n, x) = [int(y) for y in input().split()]
	a = [int(x) for x in input().split()]
	b = a
	s = 0
	u = 0
	u += sum(a)
	while b[s] % x == 0:
		b += [b[s] // x]
		u += a[s % n]
		s += 1
	print(u)


import math as mt
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	arr = []
	i = 0
	while i < n:
		element = l[i]
		cnt = 1
		i += 1
		while i < n and element == l[i]:
			cnt += 1
			i += 1
		arr.append((element, cnt))
	i = 0
	while True:
		if arr[i][0] % x == 0:
			arr.append((arr[i][0] // x, arr[i][1] * x))
			i += 1
		else:
			break
	sm = 0
	for (i, j) in arr:
		sm += i * j
	print(sm)


t = int(input())
for _ in range(t):
	(n, x) = list(map(int, input().strip().split()))
	nums = list(map(int, input().strip().split()))
	currsum = sum(nums)
	nums = [(e, 1) for e in nums]
	index = 0
	while index < len(nums):
		(val, cnt) = nums[index]
		if val % x != 0:
			break
		else:
			diff = val // x
			nums.append((val // x, cnt * x))
			currsum += val // x * cnt * x
		index += 1
	print(currsum)


import sys
sys.setrecursionlimit(10 ** 6)
fastinput = sys.stdin.readline
fastout = sys.stdout.write
t = int(fastinput())

def depth(y, x):
	depth = 0
	while y % x == 0:
		y = y // x
		depth += 1
	return depth
while t:
	t -= 1
	(n, x) = map(int, fastinput().split())
	a = list(map(int, fastinput().split()))
	mindepth = depth(a[0], x)
	index = 0
	for i in range(1, n):
		tempdepth = depth(a[i], x)
		if tempdepth < mindepth:
			if mindepth != tempdepth:
				index = i
			mindepth = tempdepth
	result = 0
	for i in range(n):
		result += a[i] * (mindepth + 1)
	for i in range(index):
		result += a[i]
	print(result)


def numpow(num, exp):
	cnt = 1
	while num % exp == 0:
		num //= exp
		cnt += 1
	return cnt
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	(tot, m, idx) = (0, 10 ** 9, -1)
	cn = [numpow(a[0], x)] + [1] * (n - 1)
	for i in range(n):
		cur = numpow(a[i], x)
		if cur < m:
			m = cur
			idx = i
	for i in range(idx):
		cn[i] = m + 1
	for i in range(idx, n):
		cn[i] = m
	for i in range(n):
		tot += a[i] * cn[i]
	print(tot)


import sys
input = sys.stdin.readline

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

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

class Solution:

	def solve(self, string_list, x):
		ans = []
		new = string_list[:]
		for i in range(len(string_list)):
			p = 0
			while string_list[i] % x == 0:
				p += 1
				string_list[i] = string_list[i] // x
			ans.append(p + 1)
		idx = ans.index(min(ans))
		sum_ = 0
		for i in range(len(new)):
			if i < idx:
				sum_ += new[i] * (ans[idx] + 1)
			else:
				sum_ += new[i] * ans[idx]
		return sum_
t = inp()
A = Solution()
for i in range(t):
	(n, x) = invr()
	string_list = inlt()
	sum_ = A.solve(string_list, x)
	print(sum_)


from sys import stdin, stdout
import math
import heapq
import collections
input = stdin.readline

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 inputstrings():
	return [x for x in input().split()]

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
t = int(input())
for q in range(t):
	(n, x) = inputnums()
	a = inputlist()
	sm = sum(a)
	ind = -1
	mn = 1000000000.0
	for i in range(n):
		cur = 0
		N = a[i]
		while N % x == 0:
			cur += 1
			N //= x
		if cur < mn:
			ind = i
			mn = cur
	sm *= mn + 1
	for i in range(ind):
		sm += a[i]
	print(sm)


import sys
t = int(input())
for _ in range(t):
	(n, x) = map(int, input().split())
	l1 = list(map(int, input().split()))
	ii = -1
	temp = sys.maxsize
	k = 0
	for i in range(n):
		c = 0
		k = l1[i]
		while k % x == 0:
			c += 1
			k //= x
		if c < temp:
			temp = c
			ii = i
	ans = 0
	cnt = 0
	for i in range(n):
		if i < ii:
			f = x
			cnt = temp + 1
			ans += l1[i] * (cnt + 1)
		else:
			f = x
			cnt = temp
			ans += l1[i] * (cnt + 1)
	print(ans)


import math
t = int(input())
for _ in range(t):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	p = []
	for i in l:
		m = i
		xx = 1
		while m % x == 0:
			m = m // x
			xx += 1
		p.append(xx)
	ans = 0
	x = min(p)
	y = x
	x = p.index(x)
	for i in range(x, n):
		p[i] = y
	if p[0] > y + 1:
		p[0] = y + 1
	for i in range(1, x):
		if p[i] > p[i - 1]:
			p[i] = p[i - 1]
	for i in range(n):
		ans += l[i] * p[i]
	print(ans)


a = int(input())
for i in range(a):
	(s, x) = map(int, input().split())
	z = list(map(int, input().split()))
	alpha = z.copy()
	ans = []
	for i in range(len(z)):
		cnt = 0
		while z[i] % x == 0:
			cnt += 1
			z[i] = z[i] // x
		ans.append(cnt)
	r = ans.index(min(ans))
	z = alpha
	q = min(ans)
	total = 0
	for i in range(len(z)):
		if i < r:
			total += z[i] * (q + 2)
		if i >= r:
			total += z[i] * (q + 1)
	print(total)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	c = 0
	for i in l:
		if i % x == 0:
			l.append(i // x)
		else:
			break
	for i in range(len(l)):
		c += l[i % n]
	print(c)


import sys
input = sys.stdin.readline
ins = lambda : input().rstrip()
ini = lambda : int(input().rstrip())
inm = lambda : map(int, input().rstrip().split())
inl = lambda : list(map(int, input().split()))
out = lambda x, s='\n': print(s.join(map(str, x)))
t = ini()
ans = []
for _ in range(t):
	(n, x) = inm()
	a = inl()
	b = []
	count = 1
	last = a[0]
	for i in range(1, n):
		if a[i] == a[i - 1]:
			count += 1
		else:
			b.append((last, count))
			count = 1
			last = a[i]
	b.append((last, count))
	count = 0
	i = 0
	while i < len(b):
		if b[i][0] % x == 0:
			b.append((b[i][0] // x, b[i][1] * x))
		else:
			break
		i += 1
	for i in b:
		count += i[0] * i[1]
	ans.append(count)
out(ans)


def do(n, x, nums) -> int:
	ans = 0
	i = 1
	while 1:
		for j in nums:
			if j % i:
				return ans
			ans += j
		i *= x
for _ in range(int(input())):
	(n, x) = list(map(int, input().split()))
	nums = [int(x) for x in input().split()]
	print(do(n, x, nums))


t = int(input())
for _ in range(t):
	(_, x) = (int(val) for val in input().split(' '))
	a_collection = input().split()
	shrunk_a_collection = [[int(a_collection[0]), 1]]
	prev = a_collection[0]
	for a in a_collection[1:]:
		if a == prev:
			shrunk_a_collection[-1][1] += 1
		else:
			shrunk_a_collection.append([int(a), 1])
		prev = a
	i = 0
	res = 0
	robot_is_active = True
	while i < len(shrunk_a_collection):
		item = shrunk_a_collection[i]
		res += item[0] * item[1]
		if robot_is_active and item[0] % x == 0:
			shrunk_a_collection += [[item[0] // x, item[1] * x]]
		else:
			robot_is_active = False
		i += 1
	print(res)


import sys
from array import *
from bisect import *
from collections import *
from functools import *
from itertools import *
from math import *
from pprint import PrettyPrinter
from typing import *
rl = lambda : [int(s) for s in input().split()]
re = lambda : int(input())
pp = PrettyPrinter().pprint
p = print

class ps:
	_cache = []

	def __init__(self, *args, **kwargs) -> None:
		ps._cache.append((args, kwargs))

	@classmethod
	def flush(cls: Type) -> None:
		for (args, kwargs) in cls._cache:
			p(*args, **kwargs)

def log_recursion_error(fn):

	@wraps(fn)
	def wrapper(*args, **kwargs):
		try:
			return fn(*args, **kwargs)
		except RecursionError as e:
			print('Encounter RecursionError')
			sys.exit(200)
	return wrapper

@log_recursion_error
def solution() -> None:
	(n, x) = rl()
	arr = rl()
	layer = 0
	stop = n
	while True:
		is_stop = False
		for (idx, elem) in enumerate(arr):
			if elem // x ** layer % x != 0:
				stop = idx
				is_stop = True
				break
		if is_stop:
			break
		else:
			layer += 1
	ps((layer + 1) * sum(arr) + sum(arr[:stop]))

def main() -> None:
	t = int(input())
	for _ in range(t):
		solution()
	ps.flush()
main()


for j in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	k = []
	w = 0
	i = 0
	s = n - 1
	y = x
	while i < len(l):
		if l[i] % x != 0:
			break
		if l[i] % x == 0:
			l += [l[i]]
		if i == s:
			x = x * y
			s += len(l) - s - 1
		i += 1
	print(sum(l))


import math
t = int(input().strip())
for k in range(t):
	(n, x) = map(int, input().strip().split())
	l = list(map(int, input().strip().split()))
	u = 1
	ans = 0
	ret = False
	while True:
		for num in l:
			if num % u == 0:
				ans += num
			else:
				ret = True
				break
		if ret:
			break
		u *= x
	print(ans)


def fxn(num, x):
	cnt = 0
	while num % x == 0:
		cnt += 1
		num //= x
	return cnt
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	d = [fxn(num, x) for num in l]
	m = min(d)
	j = d.index(m)
	ans = sum(l) * (m + 1)
	ans += sum(l[:j])
	print(ans)


import sys
input = sys.stdin.readline
from collections import *
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = sum(a)
	q = deque([])
	for ai in a:
		q.append((ai, 1))
	while q:
		(v, c) = q.popleft()
		if v % x != 0:
			break
		ans += v * c
		q.append((v // x, c * x))
	print(ans)


from sys import stdout, stdin
input = stdin.readline
print = stdout.write

def main():
	mp = lambda : map(int, input().strip().split())
	it = int
	t = it(input())
	for _ in [0] * t:
		(n, x) = mp()
		m = n
		a = list(mp())
		s = 0
		i = 0
		while i < m:
			if i >= n:
				if a[i][0] % x == 0:
					a.append((a[i][0] // x, a[i][1] * x))
					m += 1
				else:
					break
			elif a[i] % x == 0:
				a.append((a[i] // x, x))
				m += 1
			else:
				break
			i += 1
		for i in range(len(a)):
			if i < n:
				s += a[i]
			else:
				s += a[i][0] * a[i][1]
		print(str(s) + '\n')
main()


t = int(input())
for k in range(t):
	(n, x) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = [(1, item) for item in a]
	ans = 0
	for (count, item) in b:
		if item % x == 0:
			b.append((x * count, item // x))
		else:
			break
	for (count, item) in b:
		ans += count * item
	print(ans)


def func(num):
	global x
	c = 1
	while num % x == 0:
		c += 1
		num //= x
	else:
		return c

def Solve():
	global x
	for t in range(int(input())):
		(n, x) = map(int, input().split())
		a = list(map(int, input().split()))
		b = list(map(func, a))
		min_ = min(b)
		index_ = b.index(min_)
		Sum = sum(a[:index_]) * (min_ + 1) + sum(a[index_:]) * min_
		print(Sum)
Solve()


T = int(input())
for _ in range(T):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	cnt = []
	pos = 0
	for i in range(n):
		j = a[i]
		tot = 0
		while j % x == 0 and j > 0:
			j /= x
			tot += 1
		cnt.append(tot)
		if cnt[pos] > cnt[i]:
			pos = i
	s = sum(a[:pos]) * (cnt[pos] + 2) + sum(a[pos:]) * (cnt[pos] + 1)
	print(s)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = [int(i) for i in input().split()]
	b = []
	mini = 10 ** 6
	ind = -1
	for i in range(n):
		q = a[i]
		y = 1
		while q % x == 0:
			q //= x
			y += 1
		b.append(y)
		if y < mini:
			ind = i
			mini = y
	print(mini * sum(a) + sum(a[:ind]))


def padic(num, xx):
	total = 0
	while num % xx == 0:
		num = num // xx
		total += 1
	return total
for _ in range(int(input())):
	(n, xx) = [int(x) for x in input().split()]
	nums = [int(x) for x in input().split()]
	num2s = [padic(x, xx) for x in nums]
	print((min(num2s) + 1) * sum(nums) + sum(nums[:num2s.index(min(num2s))]))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = [int(x) for x in input().split()]
	arr = [int(x) for x in input().split()]
	ans = 0
	ind = -1
	res = 1000000000000
	for i in range(n):
		now = 1
		curr = arr[i]
		while curr % k == 0:
			now += 1
			curr = curr // k
		if now < res:
			res = now
			ind = i
	for i in range(n):
		if i < ind:
			ans += (res + 1) * arr[i]
		else:
			ans += res * arr[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')
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = [*map(int, input().split())]
	Ma = max(a)
	px = [None for i in range(35)]
	px[0] = 1
	for i in range(1, 35):
		px[i] = px[i - 1] * x
		if px[i] > 10 ** 19:
			break
	px = [i for i in px if i != None]
	lpx = len(px)
	ac = [None for i in range(n)]
	for i in range(n):
		j = 1
		while True:
			if a[i] % px[j] == 0:
				j += 1
			else:
				break
		ac[i] = j - 1
	ans = 0
	mac = min(ac)
	mac_reached = False
	for i in range(n):
		if ac[i] == mac:
			mac_reached = True
		if mac_reached == False:
			ans += (mac + 2) * a[i]
		else:
			ans += (mac + 1) * a[i]
	print(ans)


def main():
	n = int(input())
	ret = []
	for _ in range(n):
		(n, x) = map(int, input().split())
		a = [int(i) for i in input().split()]
		s = sum(a)
		for i in range(1, 30):
			xi = x ** i
			for v in a:
				if v % xi == 0:
					s += v
				else:
					break
			else:
				continue
			break
		ret.append(s)
	print('\n'.join(map(str, ret)))
main()


for _ in range(int(input())):
	matrix = dict()
	(n, x) = map(int, input().split())
	arr = list(map(int, input().split()))
	bj = float('inf')
	j = 0
	s = 0
	for i in range(len(arr)):
		s += arr[i]
		k = 0
		ele = arr[i]
		while not ele % x:
			if ele in matrix:
				k = k + matrix[ele]
				matrix[arr[i]] = k
				break
			ele = ele // x
			k += 1
			if k >= bj:
				break
		matrix[arr[i]] = k
		if k < bj:
			bj = k
			j = i
	res = (bj + 1) * s
	for i in arr[0:j]:
		res += i
	print(res)


t = int(input())
for _ in range(t):
	(n, x) = [int(z) for z in input().split()]
	a = [int(x) for x in input().split()]
	minCycles = float('inf')
	minCycIdx = -1
	for (i, z) in enumerate(a):
		nCycles = 0
		while z % x == 0:
			nCycles += 1
			z //= x
		if nCycles < minCycles:
			minCycles = nCycles
			minCycIdx = i
	ans = 0
	for (i, z) in enumerate(a):
		if i < minCycIdx:
			minCycles2 = minCycles + 1
		else:
			minCycles2 = minCycles
		ans += z
		cycCnt = 0
		z2 = z
		while z2 % x == 0 and cycCnt < minCycles2:
			ans += z
			z2 //= x
			cycCnt += 1
	print(ans)


def taskB(a, x):
	sum = 0
	init_length = len(a)
	i = 0
	divs = []
	counter = 1
	same_key = 1
	while i < init_length - 1:
		if a[i] == a[i + 1]:
			same_key = 1
			counter += 1
			i += 1
			continue
		else:
			sum += counter * a[i]
			if a[i] % x == 0:
				sum += counter * a[i]
				divs.append([a[i] / x, counter * x])
				same_key = 0
				counter = 1
			else:
				for f in range(i + 1, init_length):
					sum += a[f]
				return sum
		i += 1
	sum += counter * a[i]
	if a[i] % x == 0:
		sum += counter * a[i]
		divs.append([a[i] / x, counter * x])
	else:
		return sum
	if i == init_length - 1:
		i = 0
		while i < len(divs):
			if divs[i][0] % x == 0:
				divs.append([divs[i][0] / x, divs[i][1] * x])
				sum += divs[i][0] * divs[i][1]
			else:
				break
			i += 1
	return sum
t = int(input())
for i in range(t):
	x = int(input().split()[-1])
	a = list(map(lambda X: int(X), input().split()))
	print(int(taskB(a, x)))


import sys

def main():
	t = Iint()
	for _ in range(t):
		(n, x) = Imap()
		a = Ilist()
		mul_by = [1] * n
		p = x
		while True:
			for (i, ai) in en(a):
				if ai % p == 0:
					mul_by[i] += 1
				else:
					break
			else:
				p *= x
				continue
			break
		print(sum(map(int.__mul__, mul_by, a)))
FIO = 10

def debug(*args, c=6):
	starter = '\x1b[3{}m'.format(c)
	ender = '\x1b[0m'
	if c == 0:
		(starter, ender) = ('', '')
	print(starter, *args, ender, file=sys.stderr, sep='')
BUFSIZE = 8 * 1024
en = enumerate
inf = float('inf')

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()


def solve():
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	count = [0] * n
	for i in range(n):
		d = a[i]
		cnt = 1
		while d % x == 0:
			cnt += 1
			d //= x
		count[i] = cnt
	ans = 0
	current_min = 31
	global_min = min(count)
	for i in range(n):
		current_min = min(current_min, global_min + 1, count[i])
		ans += a[i] * current_min
	print(ans)
t = int(input())
for _ in range(t):
	solve()


import math
sa = lambda : input()
sb = lambda : int(input())
sc = lambda : input().split()
sd = lambda : list(map(int, input().split()))
se = lambda : float(input())
sf = lambda : list(input())

def hnbhai():
	(n, x) = sd()
	a = sd()
	d = list()
	for i in range(n):
		d.append(a[i])
	sum_ = sum(a)
	b = 0
	while b != 1:
		for i in range(n):
			if a[i] % x == 0:
				sum_ += d[i]
				a[i] = a[i] // x
			else:
				b = 1
				break
	print(sum_)
for _ in range(sb()):
	hnbhai()


def main():
	t = int(input())
	for _ in range(t):
		(n, x) = map(int, input().split())
		a = list(map(int, input().split()))
		l = []
		mx = 0
		for i in range(n):
			e = a[i]
			p = 0
			while e % x == 0:
				p += 1
				e //= x
			l.append(p + 1)
			if l[i] < l[mx]:
				mx = i
		suma = sum(a)
		total = suma * l[mx]
		for j in range(mx):
			total += a[j]
		print(total)
main()


import math
t = int(input())
for i in range(t):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	d = []
	for j in l:
		c = 0
		while j % x == 0:
			c = c + 1
			j = j // x
		d.append(c)
	m = min(d)
	p = d.index(m)
	an = sum(l) * (m + 1)
	an = an + sum(l[:p])
	print(an)


from math import ceil
t = int(input())
for _ in range(t):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	s = sum(a)
	d = x
	p = 1
	while p:
		for i in a:
			if i % d:
				p = 0
				break
			else:
				s += i
		d *= x
	print(s)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	s = sum(a)
	b = []
	for p in a:
		c = 0
		while p % x == 0:
			p //= x
			c += 1
		b.append(c)
	least = min(b)
	k = b.index(least)
	print(s + s * least + sum(a[:k]))


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	nums = [tuple((int(t), 1)) for t in input().split()]
	for t in nums:
		if not t[0] % x:
			nums.append(tuple((t[0] // x, t[1] * x)))
		else:
			print(sum(map(lambda s: s[0] * s[1], nums)))
			break


for j in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(map(int, input().split()))
	mc = 10 ** 9
	a = 0
	s = 0
	index = 0
	for i in range(n):
		a = l[i]
		c1 = 0
		while a % x == 0:
			c1 += 1
			a = a // x
		if c1 < mc:
			mc = c1
			index = i
		if mc == 0:
			break
	s = sum(l) * (mc + 1)
	for i in range(n):
		if i != index:
			s += l[i]
		else:
			break
	print(s)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	index = None
	level = float('inf')
	dic = {}
	for i in range(n):
		m = a[i]
		if dic.get(m, 'False') == True:
			continue
		c = 0
		while True:
			if m == 0 or m % x != 0:
				break
			m = m // x
			c += 1
			if c >= level:
				break
		if c < level:
			level = c
			index = i
		dic[a[i]] = True
	s = sum(a[:index]) * (level + 1) + sum(a[index:]) * level + sum(a)
	print(s)


from itertools import repeat

def get_power(n, x):
	power = 0
	while n:
		if n % x != 0:
			return power
		n //= x
		power += 1
	return power

def main():
	t = int(input())
	while t:
		t -= 1
		(n, x) = map(int, input().split())
		a = list(map(int, input().split()))
		p = list(map(get_power, a, repeat(x)))
		min_p = min(p)
		first_min_pos = p.index(min_p)
		p = [min_p + 1 if i < first_min_pos else min_p for (i, val) in enumerate(p)]
		ans = sum((a_val * (p_val + 1) for (a_val, p_val) in zip(a, p)))
		print(ans)
main()


T = int(input())
ans = ''
for _ in range(T):
	nx = [int(i) for i in input().split()]
	n = nx[0]
	x = nx[1]
	a = [int(i) for i in input().split()]
	s = 0
	p = 0
	p_pos = 0
	t = a[0]
	while t % x == 0:
		t //= x
		p += 1
	for i in range(n - 1):
		pi = 0
		t = a[i + 1]
		while t % x == 0:
			t //= x
			pi += 1
		if pi < p:
			p = pi
			p_pos = i + 1
	for i in range(n):
		if i < p_pos:
			s += (p + 2) * a[i]
		else:
			s += (p + 1) * a[i]
	ans += str(s) + '\n'
print(ans)


import sys
input = sys.stdin.readline
import math

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

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

def fac(a, b):
	k = 0
	while True:
		if a % b == 0:
			k += 1
			a = a / b
		else:
			return k
for _ in range(inp()):
	(n, x) = invr()
	l = inlt()
	f = []
	for i in range(n):
		f.append(fac(l[i], x))
	i = 0
	s = 0
	while True:
		if f[i % n] != 0:
			f[i % n] -= 1
			s = s + l[i % n]
		else:
			break
		i = i + 1
	print(s + sum(l))


from io import BytesIO, IOBase
import sys
import math
import os
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 solve():
	(n, x) = map(int, input().split())
	(*a,) = map(int, input().split())
	powers = [0] * n
	for k in range(n):
		i = a[k]
		pow = 0
		while i % math.pow(x, pow + 1) == 0:
			pow += 1
		powers[k] = pow
	minPowers = min(powers)
	ans = (minPowers + 1) * sum(a)
	if powers[0] != minPowers:
		ans += sum(a[:powers.index(minPowers)])
	print(ans)

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


R = lambda : map(int, input().split())
for _ in range(int(input())):
	(n, x) = R()
	a = list(R())
	b = a.copy()
	ans = sum(a)
	f = True
	while f:
		for i in range(n):
			if not a[i] % x:
				a[i] //= x
				ans += b[i]
			else:
				f = False
				break
	print(ans)


import math

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

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

def calc(q, x):
	ans = 0
	while q % x == 0:
		ans += 1
		q = q // x
	return ans
for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	bj = 1000000000.0 + 1
	j = 0
	for i in range(n):
		if calc(a[i], x) < bj:
			bj = calc(a[i], x)
			j = i
	s1 = (bj + 1) * sum(a)
	s2 = sum(a[:j])
	print(s1 + s2)


def get_power(val, x):
	temp = 0
	while val % x == 0:
		temp += 1
		val = val // x
	return temp
for t in range(int(input())):
	(n, x) = list(map(int, input().split()))
	nums = list(map(int, input().split()))
	power = [0] * n
	min_power = get_power(nums[0], x)
	min_index = 0
	for i in range(1, n):
		if min_power == 0:
			break
		temp = get_power(nums[i], x)
		power[i] = x
		if temp < min_power:
			min_index = i
			min_power = temp
	result = 0
	for i in range(n):
		result += (min_power + 1) * nums[i]
	for i in range(min_index):
		result += nums[i]
	print(result)


import math
import sys

def input_int():
	return int(input())

def input_list():
	return input().split(' ')

def input_list_int():
	return list(map(int, input_list()))

def z_func(s):
	n = len(s)
	z = [0] * n
	l = r = 0
	for i in range(1, n):
		if r >= i:
			z[i] = min(z[i - l], r - i + 1)
		while z[i] + i < n and s[z[i]] == s[z[i] + i]:
			z[i] += 1
		if i + z[i] - 1 > r:
			l = i
			r = i + z[i] - 1
	return z

def solve():
	(n, x) = input_list_int()
	a = input_list_int()
	tmp = {}
	for i in range(n):
		tmp[i] = 1
		v = a[i]
		while v % x == 0:
			tmp[i] += 1
			v = v / x
	mn = min(tmp.values())
	pl = 1
	ans = 0
	for i in range(n):
		if tmp[i] == mn:
			pl = 0
		ans += a[i] * (mn + pl)
	print(ans)
query_count = input_int()
while query_count:
	query_count -= 1
	solve()


import math

def strange_list(nums, x):
	x_factor = float('inf')
	x_index = None
	for (index, num) in enumerate(nums):
		value = 0
		tmp = num
		while tmp % x == 0:
			tmp = tmp / x
			value += 1
		if value < x_factor:
			x_factor = value
			x_index = index
		if value == 0:
			break
	return sum((num * (x_factor + 1) for num in nums)) + sum((num for num in nums[:x_index]))
num_test = int(input())
for i in range(num_test):
	(n, x) = [int(i) for i in input().split()]
	nums = [int(i) for i in input().split()]
	print(strange_list(nums, x))


def solver(nums, divide, length):
	orig_nums = nums
	times = 1
	orig_sum = sum(nums)
	divisible_check = [i % divide for i in nums]
	sum_check = sum(divisible_check)
	while sum_check == 0:
		times = times + 1
		nums = [i / divide for i in nums]
		divisible_check = [i % divide for i in nums]
		sum_check = sum(divisible_check)
	total = orig_sum * times
	for y in range(length):
		if divisible_check[y] == 0:
			total = total + orig_nums[y]
		else:
			return int(total)
	return int(total)
n = int(input())
for x in range(n):
	inputs = input().split(' ')
	inputs = [int(i) for i in inputs]
	nums = input().split(' ')
	nums = [int(i) for i in nums]
	print(solver(nums, inputs[1], inputs[0]))


import math
import sys
input = sys.stdin.readline
from collections import Counter, defaultdict, deque

def f(n, x, a):
	ans = 0
	lvl = [0 for i in range(n)]
	for i in range(n):
		tn = a[i]
		while tn > 0:
			if tn % x == 0:
				tn = tn // x
				lvl[i] += 1
			else:
				break
	minlvl = float('inf')
	minpos = -1
	for i in range(n):
		if lvl[i] < minlvl:
			minlvl = lvl[i]
			minpos = i
	for i in range(n):
		if minpos > i:
			ans += (minlvl + 2) * a[i]
		else:
			ans += (minlvl + 1) * a[i]
	return ans
t = int(input())
result = []
for i in range(t):
	(n, x) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	result.append(f(n, x, a))
for i in range(t):
	print(result[i])


import sys
input = sys.stdin.readline

def solve(n, x, a):
	a = [(z, 1) for z in a]
	i = 0
	s = 0
	while i < len(a):
		if a[i][0] % x != 0:
			break
		else:
			a.append((a[i][0] // x, a[i][1] * x))
		i += 1
	return sum([z[0] * z[1] for z in a])
t = int(input())
for case in range(t):
	(n, x) = [int(s) for s in input().split(' ')]
	a = [int(s) for s in input().split(' ')]
	ans = solve(n, x, a)
	print(ans)


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()

def FACT(n, mod):
	s = 1
	facts = [1]
	for i in range(1, n + 1):
		s *= i
		s %= mod
		facts.append(s)
	return facts[n]

def C(n, k, mod):
	return FACT(n, mod) * pow(FACT(k, mod) * FACT(n - k, mod) % mod, mod - 2, mod) % mod
t = II()
for _ in range(t):
	(n, x) = MI()
	a = LI()
	ans = 0
	p = [1 for i in range(n)]
	i = 0
	while i < len(a):
		if a[i] % x == 0:
			a.append(a[i] // x)
			p.append(p[i] * x)
		else:
			break
		i += 1
	ans = 0
	for i in range(len(a)):
		ans += a[i] * p[i]
	print(ans)


tcs = int(input())
for tc in range(tcs):
	(n, x) = list(map(int, input().split()))
	li = list(map(int, input().split()))
	ans = 0
	a = 1
	flag = False
	while 1:
		for i in li:
			if i % a == 0:
				ans += i
			else:
				flag = True
				break
		a *= x
		if flag:
			break
	print(ans)


for i in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	(ans, mi, midx) = (0, 10 ** 10, n - 1)
	for i in range(n):
		y = a[i]
		cnt = 0
		while True:
			if y % x:
				break
			else:
				cnt += 1
				y /= x
		if cnt < mi:
			mi = cnt
			midx = i
	for i in a:
		ans += (mi + 1) * i
	for i in range(midx):
		ans += a[i]
	print(ans)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	a = list(map(int, input().split()))
	x_power = [0] * n
	i = 0
	min_pow = 0
	for i in range(n):
		power = 0
		r = a[i]
		while r % x == 0:
			power += 1
			r = r // x
		x_power[i] = power
		if x_power[i] < x_power[min_pow]:
			min_pow = i
	s = sum(a) * (x_power[min_pow] + 1)
	for i in range(min_pow):
		s += a[i]
	print(s)


def v(a, b):
	k = 0
	while a % b == 0:
		k += 1
		a = int(a / b)
	return k
t = int(input(''))
for y in range(0, t):
	(n, x) = map(int, input('').split())
	a = list(map(int, input('').split()))
	a_1 = list(map(v, a, [x] * n))
	m = min(a_1)
	w = a_1.index(min(a_1))
	for z in range(0, w):
		a[z] = a[z] * (m + 2)
	for z in range(w, len(a)):
		a[z] = a[z] * (m + 1)
	print(sum(a))