You have a bag of size $n$. Also you have $m$ boxes. The size of $i$-th box is $a_i$, where each $a_i$ is an integer non-negative power of two.

You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.

For example, if $n = 10$ and $a = [1, 1, 32]$ then you have to divide the box of size $32$ into two parts of size $16$, and then divide the box of size $16$. So you can fill the bag with boxes of size $1$, $1$ and $8$.

Calculate the minimum number of divisions required to fill the bag of size $n$.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.

The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 10^{18}, 1 \le m \le 10^5$) — the size of bag and the number of boxes, respectively.

The second line of each test case contains $m$ integers $a_1, a_2, \dots , a_m$ ($1 \le a_i \le 10^9$) — the sizes of boxes. It is guaranteed that each $a_i$ is a power of two.

It is also guaranteed that sum of all $m$ over all test cases does not exceed $10^5$.


-----Output-----

For each test case print one integer — the minimum number of divisions required to fill the bag of size $n$ (or $-1$, if it is impossible).


-----Example-----
Input
3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8

Output
2
-1
0

Difficulty: HARD

Solutions:
def move(i):
	if lis[i + 1] >= 1:
		lis[i + 1] -= 1
		lis[i] += 2
		return 1
	else:
		ret = move(i + 1)
		lis[i + 1] -= 1
		lis[i] += 2
		return ret + 1
import math
t = int(input())
dic = {}
rdic = {}
for i in range(61):
	dic[2 ** i] = i
	rdic[i] = 2 ** i
for loop in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if sum(a) < n:
		print(-1)
		continue
	lis = [0] * 62
	ans = 0
	for i in a:
		lis[dic[i]] += 1
	nsum = 0
	NN = 0
	for i in range(61):
		nsum += lis[i] * rdic[i]
		NN += n & rdic[i]
		if nsum >= NN:
			continue
		else:
			ans += move(i)
			nsum += rdic[i]
	print(ans)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

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

def iinp():
	return int(inp())

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

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

def lmp():
	return list(mp())

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

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

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

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

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(n, m) = mp()
	arr = lmp()
	mdn = l1d(70)
	if sum(arr) < n:
		print(-1)
		continue
	s = bin(n)[2:]
	for i in range(len(s)):
		if s[len(s) - 1 - i] == '1':
			mdn[i] = 1
	cnt = l1d(70)
	for i in arr:
		cnt[len(bin(i)) - 3] += 1
	ans = 0
	for i in range(70):
		if mdn[i]:
			if cnt[i]:
				cnt[i] -= 1
			else:
				sm = 2
				j = i - 1
				while j >= 0 and sm > 0:
					sm -= cnt[j]
					sm *= 2
					j -= 1
				if sm <= 0:
					sm = 2
					j = i - 1
					while j >= 0 and sm > 0:
						x = min(cnt[j], sm)
						sm -= x
						cnt[j] -= x
						sm *= 2
						j -= 1
				else:
					for j in range(i, 70):
						if cnt[j]:
							break
					for k in range(j, i, -1):
						cnt[k] -= 1
						cnt[k - 1] += 2
					if cnt[i]:
						cnt[i] -= 1
						ans += j - i
	print(ans)


from math import log2
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	bit = [0] * 61
	sum = 0
	for x in map(int, input().split()):
		bit[int(log2(x))] += 1
		sum += x
	if sum < n:
		print(-1)
		continue
	else:
		(index, res) = (0, 0)
		while index < 60:
			if 1 << index & n != 0:
				if bit[index] > 0:
					bit[index] -= 1
				else:
					while index < 60 and bit[index] == 0:
						index += 1
						res += 1
					bit[index] -= 1
					continue
			bit[index + 1] += bit[index] // 2
			index += 1
	print(res)


import sys
input = sys.stdin.readline

def solve():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	cnt = [0] * 64
	for i in range(m):
		cnt[a[i].bit_length() - 1] += 1
	sum = 0
	ans = 0
	for j in range(64):
		bit = 1 << j
		sum += cnt[j] * bit
		if bit & n:
			if sum >= bit:
				sum -= bit
			else:
				found = False
				for k in range(j + 1, 64):
					if cnt[k] > 0:
						found = True
						cnt[k] -= 1
						break
				if not found:
					ans = -1
					break
				sum += 1 << k
				ans += k - j
				sum -= bit
	print(ans)
T = int(input())
for t in range(T):
	solve()


def solve(n, arr):
	if sum(arr) < n:
		return -1
	m = len(arr)
	bits = [0] * 61
	for num in arr:
		bits[num.bit_length() - 1] += 1
	i = 0
	l = n.bit_length()
	res = 0
	while i < l:
		if n >> i & 1:
			if bits[i]:
				bits[i] -= 1
			else:
				while bits[i] == 0:
					i += 1
					res += 1
				bits[i] -= 1
				continue
		bits[i + 1] += bits[i] >> 1
		i += 1
	return res
tests = int(input())
for _ in range(tests):
	(n, m) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	print(solve(n, arr))


import math
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	bin = [0] * 61
	s = 0
	for i in a:
		bin[int(math.log2(i))] += 1
		s += i
	if s < n:
		print(-1)
	else:
		i = 0
		ans = 0
		while i < 60:
			if 1 << i & n != 0:
				if bin[i] > 0:
					bin[i] -= 1
				else:
					while i < 60 and bin[i] == 0:
						i += 1
						ans += 1
					bin[i] -= 1
					continue
			bin[i + 1] += bin[i] // 2
			i += 1
		print(ans)


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd, log, ceil
from collections import Counter, defaultdict
from pprint import pprint
from itertools import permutations
import heapq

def main():
	(x, n) = map(int, input().split())
	arr = list(map(int, input().split()))
	arr.sort()
	if sum(arr) < x:
		print(-1)
		return
	c = Counter(arr)
	cnt = 0
	for i in range(32):
		if x & 1 << i:
			if c[1 << i] == 0:
				c[1 << i] = 2
				for j in range(i + 1, 32):
					cnt += 1
					if c[1 << j] != 0:
						c[1 << j] -= 1
						break
					else:
						c[1 << j] += 1
			c[1 << i] -= 1
		c[1 << i + 1] += c[1 << i] // 2
		c[1 << i] -= 2 * (c[1 << i] // 2)
	print(cnt)
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())):
	main()


from math import log2
from collections import defaultdict as dd
t = int(input())
d = dd(int)
while t:
	(n, m) = map(int, input().split())
	d = dd(int)
	l = list(map(int, input().split()))
	bit = [0] * 61
	su = 0
	for i in l:
		a = int(log2(i))
		d[a] += 1
		su += i
	if su < n:
		print(-1)
		t -= 1
		continue
	i = 0
	res = 0
	while i < 60:
		if 1 << i & n != 0:
			if d[i] > 0:
				d[i] -= 1
			else:
				while i < 60 and d[i] == 0:
					i += 1
					res += 1
				d[i] -= 1
				continue
		d[i + 1] += d[i] // 2
		i += 1
	print(res)
	t -= 1


import math
import collections
t = int(input())
for _ in range(t):
	(N, m) = map(int, input().split())
	a = list(map(int, input().split()))
	a2 = [int(math.log(a[i], 2)) for i in range(m)]
	if sum(a) < N:
		print(-1)
	else:
		a2.sort()
		table = collections.defaultdict(int)
		for x in a2:
			table[x] += 1
		ans = 0
		for (i, x) in enumerate(bin(N)[2:][::-1]):
			if x == '1':
				if table[i] > 0:
					table[i] -= 1
				else:
					id = i
					while table[id] == 0:
						id += 1
					table[id] -= 1
					for j in range(id - 1, i - 1, -1):
						table[j] += 1
					ans += id - i
			if table[i] >= 2:
				table[i + 1] += table[i] // 2
				table[i] %= 2
		print(ans)


from math import ceil, gcd, sqrt

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

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

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

def si():
	return input()
for _ in range(ii()):
	(n, m) = mi()
	a = li()
	dp = [0] * 61
	if n > sum(a):
		print('-1')
		continue
	for i in a:
		s = bin(i)[2:]
		dp[len(s) - 1] += 1
	(i, res) = (0, 0)
	while i < 60:
		if 1 << i & n:
			if dp[i] > 0:
				dp[i] -= 1
			else:
				while dp[i] == 0 and i < 60:
					i += 1
					res += 1
				dp[i] -= 1
				continue
		dp[i + 1] += dp[i] // 2
		i += 1
	print(res)


def problem(n, a):
	if sum(a) < n:
		return -1
	bit = [0] * 61
	for i in a:
		bit[i.bit_length() - 1] += 1
	(i, r) = (0, 0)
	while i < 60:
		if n >> i & 1:
			if bit[i]:
				bit[i] -= 1
			else:
				flg = False
				while i < 60 and bit[i] == 0:
					(bit[i], i, r, flg) = (bit[i] + 1, i + 1, r + 1, True)
				bit[i] -= 1
				if flg:
					continue
		bit[i + 1] += bit[i] >> 1
		i += 1
	return r
for i in range(int(input())):
	n = int(input().split()[0])
	a = list(map(int, input().split()))
	print(problem(n, a))


from sys import stdin, stdout
from collections import Counter
nmbr = lambda : int(input())
lst = lambda : list(map(int, input().split()))
p2 = [1]
for i in range(64):
	p2 += [p2[-1] * 2]
for _ in range(nmbr()):
	(n, m) = lst()
	a = lst()
	d = Counter(a)
	f = 1
	ans = 0
	for bp in range(64):
		if n >> bp & 1:
			pwr = p2[bp]
			while pwr <= p2[-1] and d[pwr] == 0:
				pwr *= 2
			if d[pwr] == 0:
				f = 0
				break
			while pwr > p2[bp]:
				d[pwr] -= 1
				pwr >>= 1
				d[pwr] += 2
				ans += 1
			d[p2[bp]] -= 1
		if d[p2[bp]] > 1:
			d[p2[bp + 1]] += d[p2[bp]] // 2
			d[p2[bp]] = 0
	if f:
		print(ans)
	else:
		print(-1)


import math

def solve():
	c = [0] * 61
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	s = sum(a)
	for i in a:
		c[int(math.log2(i))] += 1
	if s < n:
		print(-1)
		return
	ans = 0
	for i in range(60):
		if n >> i & 1:
			if c[i] == 0:
				j = i + 1
				while c[j] == 0:
					j += 1
				c[j] -= 1
				j -= 1
				while j >= i:
					c[j] += 1
					ans += 1
					j -= 1
				c[i] += 1
			c[i] -= 1
		c[i + 1] += c[i] // 2
	print(ans)
t = int(input())
while t:
	t -= 1
	solve()


from collections import defaultdict

def cal(n, xs):
	i = 0
	remain = set()
	for (i, x) in enumerate(reversed(bin(n)[2:])):
		if x == '1':
			remain.add(i)
	bcnt = defaultdict(int)
	bs = sorted((x.bit_length() - 1 for x in xs))
	ans = 0
	for b in bs:
		if not remain:
			break
		if b in remain:
			remain.remove(b)
			continue
		sr = sorted(remain)
		if sr[0] < b:
			isr = 0
			ans += b - sr[0]
			while isr < len(sr) and sr[isr] < b:
				remain.remove(sr[isr])
				isr += 1
			continue
		while True:
			bcnt[b] += 1
			if bcnt[b] == 2:
				bcnt[b] = 0
				if b + 1 in remain:
					remain.remove(b + 1)
				else:
					b += 1
					continue
			break
	if remain:
		return -1
	return ans
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	xs = list(map(int, input().split()))
	print(cal(n, xs))


from sys import stdin, gettrace
from collections import Counter
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():

	def solve():
		(n, m) = map(int, input().split())
		aa = [int(a) for a in input().split()]
		if sum(aa) < n:
			print(-1)
			return
		caa = Counter(aa)
		i = 1
		res = 0
		while n > 0:
			if n % (i * 2) != 0:
				j = i
				while caa[j] == 0:
					j *= 2
					res += 1
				caa[j] -= 1
				k = i
				while k < j:
					caa[k] += 1
					k *= 2
				n -= i
			if i in caa:
				if i * 2 in caa:
					caa[i * 2] += caa[i] // 2
				else:
					caa[i * 2] = caa[i] // 2
			i = i * 2
		print(res)
	q = int(input())
	for _ in range(q):
		solve()
main()


import math
T = int(input())
for t in range(T):
	(n, m) = list(map(int, input().split()))
	v = list(map(int, input().split()))
	count = [0] * 61
	for i in range(m):
		count[round(math.log2(v[i]))] += 1
	ans = 0
	for i in range(60):
		if n % 2 == 1:
			count[i] -= 1
		if count[i] < 0:
			count[i + 1] -= 1
			ans += 1
		else:
			count[i + 1] += count[i] // 2
		count[i] = count[i] % 2
		n //= 2
	if count[60] < 0:
		print(-1)
	else:
		print(ans)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

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

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

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

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

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

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

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

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 bs(a, l, h, x):
	while l < h:
		mid = (l + h) // 2
		if a[mid] == x:
			return mid
		if a[mid] < x:
			l = mid + 1
		else:
			h = mid
	return l

def sieve(a):
	for i in range(3, 10 ** 6 + 1, 2):
		a[i] = 1
	for i in range(3, 10 ** 6 + 1, 2):
		for j in range(i * i, 10 ** 6 + 1, i):
			a[j] = 0
	a[2] = 1
	return a

def bfs(g, st):
	visited = [0] * len(g)
	visited[st] = 1
	queue = []
	queue.append(st)
	new = []
	while len(queue) != 0:
		s = queue.pop()
		new.append(s)
		for i in g[s]:
			if visited[i] == 0:
				visited[i] = 1
				queue.append(i)
	return new

def solve():
	(n, k) = sep()
	a = lis()
	s = bin(n)[2:]
	cnt = [0] * 60
	for i in range(0, k):
		x = 0
		while 2 ** x != a[i]:
			x += 1
		cnt[x] += 1
	s = s[::-1]
	ans = 0
	for i in range(0, len(s)):
		if s[i] == '1':
			if cnt[i] > 0:
				cnt[i] -= 1
			else:
				x = i + 1
				while x < len(cnt) and cnt[x] == 0:
					x += 1
				if x == len(cnt):
					print(-1)
					return
				cnt[x] -= 1
				ans += x - i
				cnt[i] += 2 ** (x - i)
				cnt[i] -= 1
		temp = cnt[i] // 2
		cnt[i] -= 2 * temp
		cnt[i + 1] += temp
	print(ans)
testcase(int(inp()))


def problem(n, a):
	if sum(a) < n:
		return -1
	bit = [0] * 61
	for i in a:
		bit[i.bit_length() - 1] += 1
	(i, r, l) = (0, 0, n.bit_length())
	while i < l:
		if n >> i & 1:
			if bit[i]:
				bit[i] -= 1
			else:
				while bit[i] == 0:
					(i, r) = (i + 1, r + 1)
				bit[i] -= 1
				continue
		bit[i + 1] += bit[i] >> 1
		i += 1
	return r
for i in range(int(input())):
	n = int(input().split()[0])
	a = list(map(int, input().split()))
	print(problem(n, a))


for _ in range(int(input())):
	(m, n) = map(int, input().split())
	a = list(map(int, input().split()))
	mark = [0] * 65
	now = 1
	for indx in range(65):
		for i in a:
			if i == now:
				mark[indx] += 1
		now <<= 1
	s = bin(m)[2:]
	s = s[::-1]
	ans = 0
	flg = 1
	carry = 0
	indx = 0
	for now in s:
		if now == '0':
			carry += (1 << indx) * mark[indx]
		elif mark[indx]:
			carry += (1 << indx) * (mark[indx] - 1)
		elif carry >= 1 << indx:
			carry -= 1 << indx
		else:
			j = indx
			while j < 65:
				if mark[j]:
					break
				j += 1
			if j == 65:
				flg = 0
				break
			mark[j] -= 1
			for h in range(j - 1, indx, -1):
				mark[h] += 1
				ans += 1
			ans += 1
		indx += 1
	if flg:
		print(ans)
	else:
		print(-1)


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	Query.append((N, M, A))
for (N, M, A) in Query:
	delta = sum(A) - N
	if delta < 0:
		print(-1)
	else:
		L = max(N, max(A)).bit_length()
		D = [0] * L
		for a in A:
			D[a.bit_length() - 1] += 1
		S = 0
		to = -1
		ans = 0
		for l in range(L):
			if to != -1 and D[l] > 0:
				ans += l - to
				to = -1
				D[l] -= 1
			S += D[l] * (1 << l)
			if 1 << l & N:
				if S >= 1 << l:
					S -= 1 << l
				elif to == -1:
					to = l
		if to != -1:
			print(-1)
		else:
			print(ans)


import math
for t in range(int(input())):
	(n, m) = map(int, input().split())
	c = [0] * 61
	s = 0
	for x in map(int, input().split()):
		c[int(math.log2(x))] += 1
		s += x
	if s < n:
		print(-1)
		continue
	(i, res) = (0, 0)
	while i < 60:
		if 1 << i & n != 0:
			if c[i] > 0:
				c[i] -= 1
			else:
				while i < 60 and c[i] == 0:
					i += 1
					res += 1
				c[i] -= 1
				continue
		c[i + 1] += c[i] // 2
		i += 1
	print(res)


import math
t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	m = int(l[1])
	arr = [0 for i in range(63)]
	l = input().split()
	li = [int(i) for i in l]
	if sum(li) < n:
		print(-1)
	else:
		res = 0
		for i in li:
			arr[int(math.log2(i))] += 1
		for i in range(62):
			if n & 1 << i:
				if arr[i] > 0:
					arr[i] -= 1
				else:
					for j in range(i + 1, 62):
						if arr[j] > 0:
							arr[j] -= 1
							break
					res += j - i
					for k in range(i, j):
						arr[k] += 1
			arr[i + 1] += arr[i] // 2
		print(res)


from collections import Counter

def solve(N, M, A):
	total = 0
	counts = Counter(A)
	for i in range(N.bit_length()):
		if N & 1 << i:
			if counts[1 << i] == 0:
				smallestKeyGreater = float('inf')
				for (k, count) in counts.items():
					if k > 1 << i and count:
						smallestKeyGreater = min(smallestKeyGreater, k)
				if smallestKeyGreater == float('inf'):
					return -1
				while counts[1 << i] == 0:
					counts[smallestKeyGreater] -= 1
					total += 1
					counts[smallestKeyGreater // 2] += 2
					smallestKeyGreater = smallestKeyGreater // 2
			counts[1 << i] -= 1
		counts[1 << i + 1] += counts[1 << i] // 2
	return total
(T,) = map(int, input().split())
for t in range(T):
	(N, M) = map(int, input().split())
	A = [int(x) for x in input().split()]
	assert len(A) == M
	ans = solve(N, M, A)
	print(ans)


import sys
input = sys.stdin.readline
import math
import copy
import collections
from collections import deque
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	if n > sum(arr):
		print(-1)
	else:
		b = bin(n)[2:]
		powers = []
		for i in range(len(b) - 1, -1, -1):
			powers.append(int(b[i]))
		counts = dict()
		for i in range(m):
			if arr[i] not in counts:
				counts[arr[i]] = 0
			counts[arr[i]] += 1
		ans = 0
		for i in range(len(powers)):
			if powers[i] == 0:
				if 2 ** i in counts:
					if 2 ** (i + 1) not in counts:
						counts[2 ** (i + 1)] = 0
					counts[2 ** (i + 1)] += counts[2 ** i] // 2
			elif powers[i] == 1:
				if 2 ** i in counts and counts[2 ** i] > 0:
					counts[2 ** i] -= 1
					if 2 ** (i + 1) not in counts:
						counts[2 ** (i + 1)] = 0
					counts[2 ** (i + 1)] += counts[2 ** i] // 2
				else:
					num = i + 1
					ans += 1
					while 2 ** num not in counts:
						ans += 1
						counts[2 ** num] = 1
						num += 1
					counts[2 ** num] -= 1
		print(ans)


import math
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	if sum(arr) < n:
		print('-1')
		continue
	fre = [0] * 64
	for val in arr:
		fre[math.floor(math.log2(val))] += 1
	mx = 1 << 64
	twos = []
	while n > 0:
		if n >= mx:
			twos.append(mx)
			n -= mx
		mx >>= 1
	twos.sort()
	summ = 0
	ans = 0
	for i in range(64):
		summ += fre[i] * (1 << i)
		fre[i] = 0
		if 1 << i not in twos:
			continue
		if summ >= 1 << i:
			summ -= 1 << i
			continue
		else:
			for j in range(i + 1, 64):
				if fre[j] != 0:
					for k in range(j - 1, i - 1, -1):
						fre[k] += 1
					ans += j - i
					fre[j] -= 1
					break
		summ += fre[i] * (1 << i)
	print(ans)


import math
T = int(input())
for _ in range(0, T):
	(n, m) = map(int, input().split())
	s = [int(x) for x in input().split()]
	tot = 0
	for i in range(0, len(s)):
		tot += s[i]
	if tot < n:
		print(-1)
	else:
		ans = 0
		x = n
		pre = []
		while x > 0:
			pre.append(int(x % 2))
			x = x // 2
		kk = [0] * 62
		for i in range(0, len(s)):
			num = int(math.log2(s[i]))
			kk[num] += 1
		for i in range(0, len(pre)):
			if pre[i] == 1:
				if kk[i] >= 1:
					kk[i] -= 1
					pre[i] = 0
		rem = 0
		for i in range(0, len(pre)):
			if pre[i] == 1:
				if rem >= 2 ** i:
					rem -= 2 ** i
					pre[i] = 0
				else:
					ptr = i
					for j in range(i + 1, len(kk)):
						if kk[j] > 0:
							ptr = j
							break
					while kk[i] == 0:
						kk[ptr] -= 1
						kk[ptr - 1] += 2
						ptr -= 1
						ans += 1
					kk[i] -= 1
					rem += kk[i] * 2 ** i
			else:
				rem += kk[i] * 2 ** i
		print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	sum_a = sum(a)
	if sum_a < n:
		print(-1)
		continue
	cnts = [0] * 40
	for i in range(m):
		bit = a[i].bit_length() - 1
		cnts[bit] += 1
	ans = 0
	for i in range(39):
		if not 1 << i & n:
			pass
		elif cnts[i] != 0:
			cnts[i] -= 1
		else:
			for j in range(i, 40):
				if cnts[j] > 0:
					cnts[j] -= 1
					break
			for k in range(i, j):
				ans += 1
				cnts[k] += 1
			cnts[i] -= 1
		if cnts[i] != 0:
			cnts[i + 1] += cnts[i] // 2
	print(ans)


I = lambda : list(map(int, input().split()))
from collections import defaultdict as dd
from math import log
(t,) = I()
while t:
	t -= 1
	(m, n) = I()
	a = I()
	if sum(a) < m:
		print(-1)
		continue
	d = dd(int)
	for i in a:
		d[int(log(i, 2))] += 1
	ans = 0
	no_way = False
	for i in range(64):
		if m >> i & 1:
			if d[i]:
				d[i] -= 1
			else:
				idx = -1
				for j in range(i + 1, 64):
					if d[j]:
						idx = j
						d[j] -= 1
						break
				ans += j - i
				if idx == -1:
					no_way = True
				for j in range(i, idx):
					d[j] += 1
		d[i + 1] += d[i] // 2
	if no_way:
		print(-1)
	else:
		print(ans)


from math import log
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [int(i) for i in input().split()]
	if sum(a) < n:
		print(-1)
		continue
	maxx = int(log(max(a), 2))
	b = [0] * (maxx + 1)
	for i in a:
		b[int(log(i, 2))] += 1
	bina = [int(i) for i in bin(n)[2:]]
	bina.reverse()
	ans = 0
	for i in range(len(bina)):
		if b[i] >= bina[i]:
			b[i] -= bina[i]
			if i + 1 < len(b):
				b[i + 1] += b[i] // 2
			else:
				b.append(b[i] // 2)
			b[i] = 0
		else:
			b[i] = 2
			for j in range(i + 1, len(b)):
				if b[j] >= 1:
					b[j] -= 1
					ans += j - i
					break
				else:
					b[j] += 1
			if b[i] >= bina[i]:
				b[i] -= bina[i]
				if i + 1 < len(b):
					b[i + 1] += b[i] // 2
				else:
					b.append(b[i] // 2)
				b[i] = 0
	print(ans)


from math import log2
for i in range(int(input())):
	(K, N) = map(int, input().split())
	L = list(map(int, input().split()))
	bit = [0] * 61
	Sum = 0
	for i in L:
		bit[int(log2(i))] += 1
		Sum += i
	if Sum < K:
		print('-1')
		continue
	i = 0
	ans = 0
	while i < 60:
		if 1 << i & K != 0:
			if bit[i] > 0:
				bit[i] -= 1
			else:
				while i < 60 and bit[i] == 0:
					ans += 1
					i += 1
				bit[i] -= 1
				continue
		bit[i + 1] += bit[i] // 2
		i += 1
	print(ans)


t = int(input())
power = {}
for i in range(30):
	power[2 ** i] = i
hyper = 30
for _ in range(t):
	ans = 0
	(n, m) = map(int, input().split())
	raw = list(map(int, input().split()))
	son = sum(raw)
	if son < n:
		print(-1)
		continue
	box = [0 for _ in range(hyper)]
	for i in range(m):
		box[power[raw[i]]] += 1
	box.reverse()
	for d in range(hyper):
		scale = 2 ** (hyper - 1 - d)
		p = n // scale
		mini = min(p, box[d])
		son -= scale * box[d]
		n -= scale * mini
		box[d] -= mini
		if son < n:
			tmp = (n - son - 1) // scale + 1
			box[d] -= tmp
			box[d + 1] += 2 * tmp
			ans += tmp
			son += tmp * scale
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	if n > sum(A):
		ans = -1
	else:
		power = [0] * 62
		for a in A:
			c = 0
			while a != 1:
				a //= 2
				c += 1
			power[c] += 1
		n_power = [0] * 62
		c = 0
		while n > 0:
			n_power[c] = n % 2
			n //= 2
			c += 1
		ans = 0
		for i in range(61):
			if n_power[i] == 0:
				if power[i] >= 2:
					power[i + 1] += power[i] // 2
			elif power[i] >= 1:
				power[i + 1] += (power[i] - 1) // 2
			else:
				for j in range(1, 62):
					if power[i + j] == 0:
						power[i + j] = 1
						ans += 1
					else:
						power[i + j] -= 1
						ans += 1
						break
	print(ans)


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

def main():
	for t in range(int(input())):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		s = sum(a)
		if s < n:
			print(-1)
		elif s == n:
			print(0)
		else:
			b = Counter(a)
			bn = bin(n)[2:]
			lbn = len(bn)
			ans = 0
			ma = max(a)
			for i in range(lbn):
				val = 1 << i
				if bn[-(i + 1)] == '1':
					if b[val] >= 1:
						b[val] -= 1
					else:
						j = val
						while j <= ma and b[j] == 0:
							ans += 1
							b[j] = 1
							j = j * 2
						b[j] -= 1
				b[2 * val] += b[val] // 2
				b[val] = b[val] % 2
			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()


from math import log2
test = int(input())
for case in range(test):
	(n, m) = map(int, input().split())
	boxes = map(int, input().split())
	c = [0] * 61
	(total, ans) = (0, 0)
	for box in boxes:
		total += box
		c[int(log2(box))] += 1
	if total < n:
		print('-1')
		continue
	for i in range(61):
		if i != 0:
			c[i] += c[i - 1] // 2
		if 1 << i & n:
			if c[i] == 0:
				for j in range(i + 1, 61):
					if c[j]:
						diff = j - i
						ans += diff
						c[i] += 1 << diff
						c[j] -= 1
						break
			c[i] -= 1
	print(ans)


from math import *
out = []
for _ in range(int(input())):
	ans = 0
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	arr = [0] * 64
	for i in a:
		arr[int(log(i, 2))] += 1
	i = 0
	while n > 0:
		if n & 1 == 1:
			if arr[i] >= 1:
				arr[i] -= 1
			else:
				j = i
				while j < 64 and arr[j] == 0:
					j += 1
				if j == 64:
					ans = -1
					break
				else:
					ans += j - i
					arr[j] -= 1
					arr[i] += 2 ** (j - i) - 1
		if i < 63:
			arr[i + 1] += arr[i] // 2
		i += 1
		n = n >> 1
	out.append(str(ans))
print('\n'.join(out))


import math
NTC = int(input())
for _ in range(NTC):
	(n, m) = map(int, input().split())
	sizes = list(map(int, input().split()))
	if sum(sizes) < n:
		print('-1')
		continue
	bits = bin(n)[2:][::-1]
	maxexp = 64
	counts = {exp: 0 for exp in range(maxexp)}
	for size in sizes:
		counts[round(math.log(size, 2))] += 1
	splits = 0
	for (exp, bit) in enumerate(bits):
		if bit == '1':
			if counts[exp] == 0:
				for bigger in range(exp + 1, maxexp):
					if counts[bigger] > 0:
						for smaller in range(exp, bigger):
							counts[smaller] += 1
							splits += 1
						counts[bigger] -= 1
						break
			else:
				counts[exp] -= 1
		counts[exp + 1] += counts[exp] // 2
	print(splits)


import sys
input = sys.stdin.readline
from collections import defaultdict
t = int(input())
for _ in range(t):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	A.sort()
	ss = 0
	bnd = [0] * 42
	r = 0
	for a in A:
		k = N & -N
		if a > k:
			r += len(bin(a)) - 2 - (len(bin(k)) - 2)
			ss += a - k
			N -= k
		else:
			ss += a
		while N:
			k = N & -N
			if k > ss:
				break
			N -= k
			ss -= k
		if not N:
			break
	if N:
		print(-1)
	else:
		print(r)


from sys import stdin, stdout
from random import shuffle
T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	cnt = [0] * 64
	for i in range(m):
		for j in range(64):
			if a[i] & 1 << j:
				cnt[j] += 1
	sum = 0
	ans = 0
	for j in range(64):
		bit = 1 << j
		sum += cnt[j] * bit
		if bit & n:
			if sum >= bit:
				sum -= bit
			else:
				found = False
				for k in range(j + 1, 64):
					if cnt[k] > 0:
						found = True
						cnt[k] -= 1
						break
				if not found:
					ans = -1
					break
				sum += 1 << k
				ans += k - j
				sum -= bit
	print(ans)


import math
for T in range(int(input().strip())):
	(n, m) = [int(i) for i in input().strip().split(' ')]
	a = [int(i) for i in input().strip().split(' ')]
	if sum(a) < n:
		print(-1)
		continue
	c = [0 for i in range(60)]
	for i in a:
		c[int(math.log2(i))] += 1
	val = 1
	ans = 0
	for i in range(60):
		if i - 1 >= 0:
			c[i] += c[i - 1] // 2
		if not val & n == 0:
			if c[i] == 0:
				j = i + 1
				while j < 60:
					if c[j] > 0:
						break
					j += 1
				c[j] -= 1
				j -= 1
				while j >= i:
					c[j] += 1
					ans += 1
					j -= 1
				c[i] += 1
			c[i] -= 1
		val = val * 2
	print(ans)


import math
import collections
import sys

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

def inti(a):
	for i in range(len(a)):
		a[i] = int(a[i])
	return a

def inp():
	a = inpu()
	a = inti(a)
	return a

def solution():
	(n, m) = map(int, input().split())
	v = [0] * 61
	s = 0
	for x in map(int, input().split()):
		v[int(math.log2(x))] += 1
		s += x
	if s < n:
		print(-1)
		return
	(i, ans) = (0, 0)
	while i < 60:
		if 1 << i & n != 0:
			if v[i] > 0:
				v[i] -= 1
			else:
				while i < 60 and v[i] == 0:
					i += 1
					ans += 1
				v[i] -= 1
				continue
		v[i + 1] += v[i] // 2
		i += 1
	print(ans)
for _ in range(int(input())):
	solution()


INF = 10 ** 10

def main():
	print = out.append
	(n, m) = get_list()
	boxes = [0] * 80
	for i in get_list():
		boxes[i.bit_length() - 1] += 1
	crr = 0
	loan = 0
	res = 0
	for (i, bit) in enumerate(reversed(bin(n)[2:].zfill(80))):
		crr //= 2
		crr += boxes[i]
		if crr > 0 and loan > 0:
			crr -= 1
			res += loan
			loan = 0
		if loan > 0:
			loan += 1
		if bit == '1':
			if crr > 0:
				crr -= 1
			elif loan == 0:
				loan = 1
	print(res) if loan == 0 else print(-1)
import sys
from collections import defaultdict, Counter
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda : int(input())
get_list = lambda : list(map(int, input().split()))
[main() for _ in range(int(input()))]
print(*out, sep='\n')


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math as mt
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 gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)
mod = int(1000000000.0) + 7

def power(k, n):
	if n == 0:
		return 1
	if n % 2:
		return power(k, n - 1) * k % mod
	t = power(k, n // 2)
	return t * t % mod

def totalPrimeFactors(n):
	count = 0
	if n % 2 == 0:
		count += 1
		while n % 2 == 0:
			n //= 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			count += 1
			while n % i == 0:
				n //= i
		i += 2
	if n > 2:
		count += 1
	return count

def main():
	for _ in range(int(input())):
		cnt = [0 for i in range(62)]
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		if sum(a) < n:
			print(-1)
			continue
		for i in a:
			for j in range(62):
				if i == 1 << j:
					cnt[j] += 1
					break
		num = []
		for i in range(62):
			if n & 1 << i:
				num.append(1)
			else:
				num.append(0)
		ans = 0
		for i in range(61):
			if cnt[i] > 2:
				t = (cnt[i] - 1) // 2
				cnt[i + 1] += t
				cnt[i] -= 2 * t
			if cnt[i] == 2 and num[i] == 0:
				cnt[i + 1] += 1
				cnt[i] = 0
			if cnt[i] == 0 and num[i] == 1:
				for j in range(i + 1, 62):
					if cnt[j] > num[j]:
						cnt[j] -= 1
						for k in range(i + 1, j):
							cnt[k] += 1
						cnt[i] += 2
						ans += j - i
						break
		for i in range(62):
			if cnt[i] == 0 and num[i] == 1:
				for j in range(i + 1, 62):
					if cnt[j] > num[j]:
						cnt[j] -= 1
						for k in range(i + 1, j):
							cnt[k] += 1
						cnt[i] += 2
						ans += j - i
						break
		print(ans)
	return
main()


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	c = 1
	if sum(a) < n:
		print(-1)
		continue
	j = 0
	a.sort()
	d = defaultdict(int)
	for i in a:
		while c < i:
			c *= 2
			j += 1
		d[j] += 1
	bit = [0] * 70
	j = 0
	copy = n
	while n > 0:
		bit[j] = n % 2
		n //= 2
		j += 1
	res = 0
	for i in range(70):
		if bit[i] == 0:
			d[i + 1] += d[i] // 2
			d[i] %= 2
		elif d[i] > 0:
			d[i] -= 1
			d[i + 1] += d[i] // 2
			d[i] %= 2
		else:
			pos = i
			for j in range(i + 1, 70):
				if d[j] > 0:
					pos = j - 1
					d[j] -= 1
					break
			while pos >= i:
				d[pos] += 1
				pos -= 1
				res += 1
	print(res)


from sys import stdin, stdout
from math import log2
T = int(stdin.readline())
for i in range(T):
	(n, m) = map(int, stdin.readline().split())
	c = [0] * 61
	s = 0
	for x in map(int, stdin.readline().split()):
		c[int(log2(x))] += 1
		s += x
	if s < n:
		stdout.write('-1\n')
		continue
	(i, res) = (0, 0)
	while i < 60:
		if 1 << i & n != 0:
			if c[i] > 0:
				c[i] -= 1
			else:
				while i < 60 and c[i] == 0:
					i += 1
					res += 1
				c[i] -= 1
				continue
		c[i + 1] += c[i] // 2
		i += 1
	stdout.write(str(res) + '\n')


from math import log
for _ in range(int(input())):
	X = list(map(int, input().split()))
	Number = list(map(int, input().split()))
	if sum(Number) < X[0]:
		print(-1)
		continue
	Size = len(bin(max(Number))) - 2
	MyCheckNumber = bin(X[0])[2:][::-1]
	MyArray = [0] * (max((Size, len(MyCheckNumber))) + 1)
	for i in Number:
		MyArray[int(log(i, 2))] += 1
	Count = 0
	for index in range(len(MyCheckNumber)):
		if MyCheckNumber[index] == '1':
			if MyArray[index] == 0:
				for i in range(index + 1, Size + 1):
					if MyArray[i] > 0:
						MyArray[i] -= 1
						for j in range(i - 1, index - 1, -1):
							MyArray[j] += 1
							Count += 1
						break
			else:
				MyArray[index] -= 1
		MyArray[index + 1] += MyArray[index] // 2
	print(Count)


import sys
from collections import defaultdict as dd
from bisect import bisect_left as bl
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	a = list(map(int, input().split()))
	res = 0
	if sum(a) < N:
		print(-1)
		continue
	t = [0] * 31
	a.sort()
	b = []
	for i in range(M):
		x = a[i]
		if x & N:
			N -= x
			continue
		for j in range(31):
			t[j] += x & 1 << j
		b.append(x)
	a = b
	cs = [0] * 32
	for j in range(31):
		cs[j + 1] = cs[j] + t[j]
	ns = []
	prev = 0
	divd = [0] * M
	for j in range(31):
		if N & 1 << j > 0:
			ns.append(j)
	for i in range(len(ns)):
		j = ns[i]
		if i > 0:
			prev += 1 << ns[i - 1]
		x = cs[j + 1] - prev
		if x < 1 << j:
			k = bl(a, 1 << j)
			y = a[k]
			res += max(0, len(bin(y)) - 2 - j - 1 - divd[k])
			divd[k] += len(bin(y)) - 2 - j - 1
	print(res)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if sum(a) < n:
		print(-1)
		continue
	c = [0] * 61
	for i in range(m):
		x = 0
		while a[i] % 2 == 0:
			a[i] //= 2
			x += 1
		c[x] += 1
	ans = 0
	i = 0
	while i < 60:
		if n >> i & 1:
			if c[i] > 0:
				c[i] -= 1
			else:
				while i < 60 and c[i] == 0:
					i += 1
					ans += 1
				c[i] -= 1
				continue
		c[i + 1] += c[i] // 2
		i += 1
	print(ans)


def log2(n):
	i = 0
	while n >> i != 1:
		i += 1
	return i

def solve(n, po2s):
	if sum(po2s) < n:
		return -1
	po_cnt = [0] * 60
	for x in po2s:
		po_cnt[log2(x)] += 1
	ans = 0
	for i in range(60):
		if n & 1 << i:
			if po_cnt[i]:
				po_cnt[i] -= 1
			else:
				j = i
				while po_cnt[j] == 0:
					j += 1
				while j > i:
					ans += 1
					po_cnt[j] -= 1
					po_cnt[j - 1] += 2
					j -= 1
				po_cnt[i] -= 1
		if i < 59:
			po_cnt[i + 1] += po_cnt[i] // 2
	return ans
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	po2s = list(map(int, input().split()))
	print(solve(n, po2s))


import sys
import math
from collections import defaultdict
from collections import deque
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
go = lambda : 1 / 0

def write(*args, sep='\n'):
	for i in args:
		sys.stdout.write('{}{}'.format(i, sep))
INF = float('inf')
MOD = int(1000000000.0 + 7)
YES = 'YES'
NO = -1
for _ in range(int(input())):
	try:
		(n, m) = read()
		arr = read()
		x = [0] * 65
		if sum(arr) < n:
			print(NO)
			go()
		for i in arr:
			x[int(math.log2(i))] += 1
		ans = 0
		for i in range(65):
			if 1 << i & n:
				if x[i] != 0:
					x[i] -= 1
					continue
				total = 0
				for j in range(i):
					total += (1 << j) * x[j]
				if total >= 1 << i:
					temp = 1 << i
					for j in reversed(range(i)):
						while temp - (1 << j) >= 0 and x[j] > 0:
							temp -= 1 << j
							x[j] -= 1
					continue
				j = i
				while j < 65 and x[j] == 0:
					j += 1
				if j == 65:
					print(NO)
					go()
				else:
					x[j] -= 1
					for k in range(i, j):
						x[k] += 1
					ans += j - i
		print(ans)
	except ZeroDivisionError:
		continue
	except Exception as e:
		print(e)
		continue


import sys
import bisect
from collections import deque

def no():
	print('NO')

def dist(z, c):
	return (z[0] - c[0]) * (z[0] - c[0]) + (z[1] - c[1]) * (z[1] - c[1])

def vec(z, c):
	return z[0] * c[1] - z[1] * c[0]

def pro(z, c):
	return [z[0] - c[0], z[1] - c[1]]

def main():
	(n, m) = [int(i) for i in sys.stdin.readline().split()]
	w = [0 for i in range(100)]
	q = [int(i) for i in sys.stdin.readline().split()]
	s = sum(q)
	res = 0
	if s == n:
		print(0)
		return 0
	if s < n:
		print(-1)
		return 0
	for i in range(m):
		for o in range(30):
			if q[i] == 1 << o:
				w[o] += 1
	for i in range(61):
		e = -1
		if n & 1 << i:
			if w[i] == 0:
				for o in range(1, i + 1):
					r = w[o - 1] // 2
					w[o - 1] -= r * 2
					w[o] += r
			if w[i] == 0:
				for o in range(i + 1, 61):
					if w[o] > 0:
						e = o
						break
			for o in range(e, i, -1):
				w[o] -= 1
				w[o - 1] += 2
				res += 1
			w[i] -= 1
	print(res)
for i in range(int(sys.stdin.readline())):
	main()


def main():
	import sys
	input = sys.stdin.readline
	t = int(input())
	for _ in range(t):
		(N, M) = map(int, input().split())
		A = list(map(int, input().split()))
		C = [0] * 100
		for a in A:
			C[a.bit_length() - 1] += 1
		ans = 0
		flg = 1
		for j in range(N.bit_length()):
			if N >> j & 1:
				if C[j]:
					C[j] -= 1
					C[j + 1] += C[j] // 2
				else:
					ok = 1
					k = j + 1
					while True:
						if C[k]:
							C[k] -= 1
							ans += k - j
							for l in range(k - 1, j - 1, -1):
								C[l] += 1
							break
						k += 1
						if k == 100:
							ok = 0
							break
					if not ok:
						flg = 0
						break
			else:
				C[j + 1] += C[j] // 2
		if flg:
			print(ans)
		else:
			print(-1)
main()


import sys
from collections import Counter

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

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

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

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

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

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

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

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

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
for _ in range(INT()):
	(N, M) = MAP()
	A = LIST()
	C = Counter(A)
	ans = 0
	for k in range(0, 61):
		if N & 1 << k:
			if C[1 << k] == 0:
				for k2 in range(k + 1, 31):
					if C[1 << k2] >= 1:
						k3 = k2
						while k3 > k:
							C[1 << k3] -= 1
							C[1 << k3 - 1] += 2
							k3 -= 1
							ans += 1
						break
				else:
					print(-1)
					break
			C[1 << k] -= 1
		C[1 << k + 1] += C[1 << k] // 2
		C[1 << k] = C[1 << k] % 2
	else:
		print(ans)


t = int(input())
for ijkl in range(t):
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	f = max(a)
	f = max(f, n)
	number = 1
	power = 2
	while power <= f:
		power = power * 2
		number += 1
	have = [0 for i in range(number)]
	for x in a:
		copy = x
		deg = 0
		while copy > 1:
			copy = copy // 2
			deg += 1
		have[deg] += 1
	numbers = [0 for i in range(number)]
	for i in range(number):
		last = n % 2
		numbers[i] = last
		n = n // 2
	ans = 0
	ok = True
	for i in range(number):
		if numbers[i] == 1:
			if have[i] >= 1:
				have[i] -= 1
			else:
				j = i + 1
				if j == number:
					ok = False
					break
				while have[j] == 0:
					j += 1
					if j == number:
						ok = False
						break
				ans += j - i
				while j > i:
					have[j] -= 1
					have[j - 1] += 2
					j = j - 1
				have[i] -= 1
		if i + 1 != number:
			have[i + 1] += have[i] // 2
			have[i] = 0
	if ok:
		print(ans)
	else:
		print(-1)


from math import log2
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	c = [0] * 61
	total = 0
	for x in map(int, input().split()):
		c[int(log2(x))] += 1
		total += x
	if total < n:
		print(-1)
	else:
		(i, ans) = (0, 0)
		while i < 60:
			if 1 << i & n != 0:
				if c[i] > 0:
					c[i] -= 1
				else:
					while i < 60 and c[i] == 0:
						i += 1
						ans += 1
					c[i] -= 1
					continue
			c[i + 1] += c[i] // 2
			i += 1
		print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	boxes = list(map(int, input().split()))
	if sum(boxes) < n:
		print(-1)
		continue
	needed = [0] * 60
	got = [0] * 60
	for b in boxes:
		got[b.bit_length() - 1] += 1
	divisions = 0
	for bit in range(60):
		if 1 << bit & n:
			if got[bit]:
				got[bit] -= 1
			else:
				for j in range(bit + 1, 60):
					divisions += 1
					if got[j]:
						got[j] -= 1
						t = j - 1
						while t > bit:
							got[t] += 1
							t -= 1
						got[t] = 1
						break
		if bit != 59:
			got[bit + 1] += got[bit] // 2
	print(divisions)


from math import factorial
from collections import Counter
from heapq import heapify, heappop, heappush
import os
import sys
from math import log2
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
inputI = int(input())
mod = 1000000007
INF = float('inf')

def main():
	N = inputI
	for _ in range(N):
		(n, m) = RL()
		rec = [0] * 33
		sm = 0
		for i in RL():
			sm += i
			rec[int(log2(i))] += 1
		if sm < n:
			print(-1)
		else:
			b = res = 0
			while b < 32:
				nb = 1 << b & n
				if nb != 0:
					if rec[b] == 0:
						bi = i + 1
						while b < 33 and rec[b] == 0:
							b += 1
							res += 1
						rec[b] -= 1
						continue
					else:
						rec[b] -= 1
				rec[b + 1] += rec[b] // 2
				b += 1
			print(res)
main()


def solve(num, arr):
	freq = [0 for i in range(64)]
	for i in arr:
		x = i
		pos = 0
		while x > 0:
			if x & 1:
				freq[pos] += 1
			x = x >> 1
			pos += 1
	if num > sum(arr):
		return -1
	ans = 0
	pos = 0
	while num > 0:
		if num & 1:
			if freq[pos] > 0:
				freq[pos] -= 1
			else:
				while pos < 64 and freq[pos] <= 0:
					ans += 1
					freq[pos] += 1
					pos += 1
					num = num >> 1
				freq[pos] -= 1
				continue
		freq[pos + 1] += freq[pos] // 2
		pos += 1
		num = num >> 1
	return ans
t = int(input())
for j in range(t):
	(num, n) = [int(ele) for ele in input().strip().split()]
	arr = [int(ele) for ele in input().strip().split()]
	print(solve(num, arr))


import math as mt
for tc in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	if sum(l) < n:
		print(-1)
		continue
	co = [0] * (10 ** 5 + 1)
	for i in l:
		co[int(mt.log2(i))] += 1
	i = 0
	ans = 0
	while i < 60:
		if 1 << i & n != 0:
			if co[i]:
				co[i] -= 1
			else:
				while i < 60 and co[i] == 0:
					ans += 1
					i += 1
				co[i] -= 1
				continue
		co[i + 1] += co[i] // 2
		i += 1
	print(ans)


from sys import stdin, stdout, setrecursionlimit
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log, log2
from random import seed, randint
from datetime import datetime
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from collections import defaultdict as dd
mod = pow(10, 9) + 7
mod2 = 998244353

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

def iinp():
	return int(inp())

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

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

def lmp():
	return list(mp())

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

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

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

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

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def def_value():
	return 0

def def_inf():
	return inf

def atoi(s):
	return ord(s) - ord('a')

def inc(s, n=1):
	return chr((ord(s) - ord('a') + n) % 26 + ord('a'))

class XY:

	def __init__(self, x, y):
		self.x = x
		self.y = y

def rotate(a, b, c):
	ang = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y)
	if ang == 0:
		return 0
	else:
		return ang / abs(ang)
for _ in range(iinp()):
	(n, m) = mp()
	a = lmp()
	cnt = 0
	if sum(a) >= n:
		p = []
		f = l1d(62)
		bits = l1d(62)
		t = n
		for i in range(1, 63):
			bits[i - 1] = t % 2
			t //= 2
		for i in range(m):
			f[int(log2(a[i]))] += 1
		i = 0
		while i < 61:
			if bits[i] == 1:
				if f[i] > 0:
					f[i] -= 1
					f[i + 1] += f[i] // 2
					f[i] %= 2
					i += 1
				else:
					j = i
					while j < 61 and f[j] == 0:
						j += 1
					cnt += j - i
					i = j
					f[i] -= 1
			else:
				f[i + 1] += f[i] // 2
				f[i] %= 2
				i += 1
		print(cnt)
	else:
		print(-1)


import sys, os, io
from sys import stdin
import math
from collections import defaultdict
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
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')
alphabets = list('abcdefghijklmnopqrstuvwxyz')
from types import GeneratorType

def bootstrap(f, stack=[]):

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

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 primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

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

def sieveForSmallestPrimeFactor():
	MAXN = 100001
	spf = [0 for i in range(MAXN)]
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, math.ceil(math.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
	return spf

def getPrimeFactorizationLOGN(x):
	spf = sieveForSmallestPrimeFactor()
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

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

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

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

def li():
	return list(map(int, input().split()))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def solve():
	(n, m) = li()
	a = li()
	if sum(a) < n:
		print(-1)
		return
	l = []
	bit = [0] * 65
	for i in a:
		l.append(int(math.log2(i)))
		bit[int(math.log2(i))] += 1
	i = 0
	ans = 0
	while i < 64:
		if 1 << i & n != 0:
			if bit[i] > 0:
				bit[i] -= 1
				bit[i + 1] += bit[i] // 2
				i += 1
			else:
				while i < 65 and bit[i] == 0:
					i += 1
					ans += 1
				bit[i] -= 1
		else:
			bit[i + 1] += bit[i] // 2
			i += 1
	print(ans)
t = 1
t = ii()
for _ in range(t):
	solve()


import sys, math
MOD = 998244353

def solve():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if sum(a) < n:
		return -1
	f = [0 for i in range(64)]
	for ai in a:
		p = 0
		while ai != 1:
			p += 1
			ai = ai >> 1
		f[p] += 1
	ans = 0
	for i in range(63):
		if 1 << i & n == 0:
			f[i + 1] += f[i] // 2
		elif f[i] == 0:
			j = i
			while f[j] == 0:
				f[j] += 1
				ans += 1
				j += 1
			f[j] -= 1
		else:
			f[i] -= 1
			f[i + 1] += f[i] // 2
	return ans
for test in range(1, int(input()) + 1):
	print(solve())


import math
num = int(input())
for _ in range(num):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	a.sort()
	ans = 0
	s = str(bin(n))[2:]
	s = s[::-1]
	ans = 0
	goukei = 0
	powlist = [0 for i in range(100)]
	for i in a:
		powlist[math.floor(math.log2(i))] += 1
	if n > sum(a):
		print(-1)
		continue
	for (i, x) in enumerate(s):
		b = powlist[i] * 2 ** i
		goukei += b
		if x == '0':
			continue
		if goukei < 2 ** i:
			pos = i
			while 1:
				powlist[pos] += 1
				pos += 1
				ans += 1
				if powlist[pos] > 0:
					powlist[pos] -= 1
					break
			goukei += 2 ** i
		else:
			goukei -= 2 ** i
	print(ans)


from math import log2

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		s = 0
		bit = [0] * 64
		for el in a:
			bit[int(log2(el))] += 1
			s += el
		if s < n:
			print(-1)
			continue
		if s == n:
			print(0)
			continue
		ans = 0
		i = 0
		while i < 63:
			if 1 << i & n:
				if bit[i]:
					bit[i] -= 1
				else:
					while i < 63 and bit[i] == 0:
						ans += 1
						i += 1
					bit[i] -= 1
					continue
			bit[i + 1] += bit[i] // 2
			i += 1
		print(ans)
main()


def main():
	T = int(input())
	for t in range(T):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		cnt = [0] * 64
		for i in range(m):
			cnt[a[i].bit_length() - 1] += 1
		sum = 0
		ans = 0
		for j in range(64):
			bit = 1 << j
			sum += cnt[j] * bit
			if bit & n:
				if sum >= bit:
					sum -= bit
				else:
					found = False
					for k in range(j + 1, 64):
						if cnt[k] > 0:
							found = True
							cnt[k] -= 1
							break
					if not found:
						ans = -1
						break
					sum += 1 << k
					ans += k - j
					sum -= bit
		print(ans)
main()


t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if n > sum(a):
		print(-1)
		continue
	last = 0
	bn = bin(n)
	ba = [len(bin(i)) - 3 for i in a]
	dig_a = [0] * 100
	for i in ba:
		dig_a[i] += 1
	ans = 0
	for i in range(len(bn) - 2):
		last = last // 2 + dig_a[i]
		if int(bn[-1 - i]) == 1:
			if last > 0:
				last -= 1
			else:
				j = 1
				while True:
					if i + j >= 100:
						break
					if dig_a[i + j] > 0:
						ans += j
						last += 2 ** j - 1
						dig_a[i + j] -= 1
						break
					else:
						j += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split(' '))
	a = list(map(int, input().strip().split(' ')))
	if sum(a) < n:
		print('-1')
		continue
	b = [0 for _ in range(64)]
	for z in a:
		for q in range(64):
			b[q] += z >> q & 1
	tar = [0 for _ in range(64)]
	for q in range(64):
		tar[q] += n >> q & 1
	for i in range(64):
		if tar[i] == 1 and b[i] >= 1:
			tar[i] -= 1
			b[i] -= 1
	splits = 0
	for i in range(63):
		if tar[i] == 0:
			continue
		for j in range(i):
			if b[j] > 1:
				b[j + 1] += b[j] // 2
				b[j] = b[j] % 2
		if tar[i] == 1 and b[i] >= 1:
			tar[i] -= 1
			b[i] -= 1
			continue
		for j in range(i + 1, 64):
			if b[j] >= 1:
				splits += 1
				b[j] -= 1
				b[i] -= 1
				break
			else:
				b[j] += 1
				splits += 1
	print(splits)


for i in range(int(input())):
	(k, n) = map(int, input().split())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		d[i] = d.get(i, 0) + 1
	i = 0
	if sum(a) < k:
		print(-1)
	else:
		nn = k
		ans = 0
		while nn > 0:
			if 1 << i & k > 0:
				if d.get(1 << i, 0) == 0:
					j = 1 << i
					while d.get(j, 0) == 0:
						j *= 2
						ans += 1
					d[j] -= 1
					while j != 1 << i:
						j //= 2
						d[j] = d.get(j, 0) + 1
				else:
					d[1 << i + 1] = d.get(1 << i + 1, 0) + (d.get(1 << i, 0) - 1) // 2
				nn -= 1 << i
			else:
				d[1 << i + 1] = d.get(1 << i + 1, 0) + d.get(1 << i, 0) // 2
			i += 1
		print(ans)


def main(n, m, a):
	j = 0
	tmp = 0
	divisions = 0
	for i in range(50):
		if n >> i & 1 == 0:
			continue
		elif tmp >> i & 1 == 1:
			tmp -= 1 << i
			continue
		elif tmp >> i & 1 == 0:
			while tmp < 1 << i:
				if j == len(a):
					return -1
				tmp += a[j]
				j += 1
			shift = 0
			while tmp >> i + shift & 1 == 0:
				shift += 1
				divisions += 1
			tmp -= 1 << i
	return divisions
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	a.sort()
	divisions = main(n, m, a)
	print(divisions)


q = int(input())
for rwrea in range(q):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	if sum(l) < n:
		print(-1)
	else:
		dick = {}
		i = 1
		while i < 10 ** 9:
			dick[i] = 0
			i *= 2
		for i in range(m):
			dick[l[i]] += 1
		potrz = {}
		i = 1
		while n > 0:
			potrz[i] = n % 2
			n //= 2
			i *= 2
		while i < 10 ** 9:
			potrz[i] = 0
			i *= 2
		for i in dick:
			odj = min(potrz[i], dick[i])
			potrz[i] -= odj
			dick[i] -= odj
		kroki = 0
		docelowy = {}
		for i in dick:
			docelowy[i] = 0
		problem = 1
		while True:
			if problem > 10 ** 9:
				break
			if potrz == docelowy:
				break
			if potrz[problem] == 0:
				j = 1
				while j <= problem:
					usu = dick[j] // 2
					try:
						dick[j] -= 2 * usu
						dick[2 * j] += usu
						j *= 2
					except Exception:
						break
				problem *= 2
			else:
				cykk = min(potrz[problem], dick[problem])
				potrz[problem] -= cykk
				dick[problem] -= cykk
			if problem > 10 ** 9:
				break
			if potrz[problem] > 0:
				j = problem
				while dick[j] == 0:
					j *= 2
				dick[j] -= 1
				while j > problem:
					kroki += 1
					j //= 2
					dick[j] += 1
				dick[j] += 1
		print(kroki)


def solve() -> None:
	n = [int(i) for i in input().split()][0]
	bs = [0] * 32
	for i in input().split():
		i = int(i)
		for bi in range(len(bs) - 1, -1, -1):
			bv = 1 << bi
			if i & bv != 0:
				bs[bi] += 1
				break
	sm = [bs[0]] * len(bs)
	for bi in range(1, len(bs)):
		bv = 1 << bi
		sm[bi] = sm[bi - 1] + bv * bs[bi]
	if sm[-1] < n:
		print('-1')
		return
	res = 0
	for bi in range(1, len(bs)):
		bv = 1 << bi
		sm[bi] = sm[bi - 1] + bv * bs[bi]
	lbi = -1
	for bi in range(len(bs) - 1, -1, -1):
		if sm[bi] < n:
			bs[bi] += 2
			res += lbi - bi
		bv = 1 << bi
		need = min(n // bv, bs[bi])
		n -= need * bv
		bs[bi] -= need
		if bs[bi] > 0:
			lbi = bi
	print(res)
t = int(input())
while t:
	t -= 1
	solve()


from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from functools import *
from itertools import permutations, combinations, groupby
import sys
import bisect
import string
import math
import time
import random

def Golf():
	(*a,) = map(int, open(0))

def S_():
	return input()

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

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

def I():
	return int(input())

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

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

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def StoI():
	return [ord(i) - 97 for i in input()]

def ItoS(nn):
	return chr(nn + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def GI(V, E, Directed=False, index=0):
	org_inp = []
	g = [[] for i in range(n)]
	for i in range(E):
		inp = LI()
		org_inp.append(inp)
		if index == 0:
			inp[0] -= 1
			inp[1] -= 1
		if len(inp) == 2:
			(a, b) = inp
			g[a].append(b)
			if not Directed:
				g[b].append(a)
		elif len(inp) == 3:
			(a, b, c) = inp
			aa = (inp[0], inp[2])
			bb = (inp[1], inp[2])
			g[a].append(bb)
			if not Directed:
				g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}):
	mp = [1] * (w + 2)
	found = {}
	for i in range(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [1] + [mp_def[j] for j in s] + [1]
	mp += [1] * (w + 2)
	return (h + 2, w + 2, mp, found)

def bit_combination(k, n=2):
	rt = []
	for tb in range(n ** k):
		s = [tb // n ** bt % n for bt in range(k)]
		rt += [s]
	return rt

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = ['YES', 'NO']
mo = 10 ** 9 + 7
inf = float('inf')
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
input = lambda : sys.stdin.readline().rstrip()

def ran_input():
	import random
	n = random.randint(4, 16)
	(rmin, rmax) = (1, 10)
	a = [random.randint(rmin, rmax) for _ in range(n)]
	return (n, a)
show_flg = False
show_flg = True
ans = 0
t = I()
for _ in range(t):
	ans = 0
	N = 70
	(n, m) = LI()
	a = LI()
	a.sort()
	dif = sum(a) - n
	if dif < 0:
		print(-1)
		continue
	D = [0] * N
	B = [0] * N
	for j in a:
		B[j.bit_length() - 1] += 1
	for i in range(N):
		if n >> i & 1:
			D[i] = 1
	j = 2 * N
	for i in range(N):
		if i > j and B[i] > 0:
			ans += i - j
			B[i] -= 1
			j = 2 * N
		if D[i] > 0:
			if B[i] > 0:
				D[i] -= 1
				B[i] -= 1
			else:
				j = min(j, i)
		if B[i] > 1:
			B[i + 1] += B[i] // 2
			B[i] -= B[i] // 2 * 2
	print(ans)


import sys
input = sys.stdin.readline
from math import *
t = int(input())
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	p = [0 for i in range(70)]
	a = [int(x) for x in input().split()]
	if sum(a) < n:
		print(-1)
		continue
	for i in a:
		p[int(log(i, 2))] += 1
	a = list(bin(n))[2:][::-1]
	d = 0
	flag = 0
	for i in range(len(a)):
		if a[i] == '1':
			c = 2 ** i
			for j in range(i, -1, -1):
				if p[j] * 2 ** j >= c:
					p[j] -= i - j + 1
					c = 0
					break
				else:
					c -= p[j] * 2 ** j
					p[j] = 0
			if c > 0:
				c = 2 ** i
				for j in range(i + 1, 70):
					if p[j] > 0:
						p[j] -= 1
						d += j - i
						for k in range(i, j):
							p[k] += 1
						c = 0
						break
			if c != 0:
				flag = 1
				break
	print(d if flag == 0 else -1)


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
import math

def lowest_pair(li):
	for i in range(61):
		if li.count(i) >= 2:
			return i
	return -1

def closest_n(li, n):
	for i in range(n, len(li)):
		if li[i]:
			return i
	return -1
for _ in range(int(input())):
	(bag_size, n_boxes) = [int(x) for x in input().split()]
	boxes = [int(x) for x in input().split()]
	log_boxes = [0] * 61
	for box in boxes:
		log_boxes[int(math.log2(box))] += 1
	if sum(boxes) < bag_size:
		print(-1)
		continue
	bin_bag = [int(x) for x in bin(bag_size)[2:][::-1]]
	divisions = 0
	while 1 in bin_bag:
		i = bin_bag.index(1)
		if log_boxes[i]:
			log_boxes[i] -= 1
			bin_bag[i] = 0
		else:
			for j in range(0, i):
				n = log_boxes[j]
				log_boxes[j] = n % 2
				log_boxes[j + 1] += n // 2
			if log_boxes[i]:
				log_boxes[i] -= 1
				bin_bag[i] = 0
			else:
				while not log_boxes[i]:
					n = closest_n(log_boxes, i)
					log_boxes[n] -= 1
					log_boxes[n - 1] += 2
					divisions += 1
				log_boxes[i] -= 1
				bin_bag[i] = 0
	print(divisions)


import math
t = int(input())
M2 = [1]
for i in range(35):
	M2.append(M2[-1] * 2)
for i in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	if sum(A) < n:
		print(-1)
	else:
		B = [0] * 33
		for i in range(m):
			B[int(math.log2(A[i]))] += 1
		C = [0] * 33
		nn = n
		for i in range(33):
			C[i] = nn % 2
			nn //= 2
			if nn == 0:
				break
		b = 0
		c = 0
		i = 0
		ans = 0
		ok = 0
		while i < len(B):
			while i < len(B) and b >= c:
				b += B[i] * M2[i]
				c += C[i] * M2[i]
				B[i] = 0
				i += 1
			if i == len(B) and b >= c:
				print(ans)
				ok = 1
				break
			else:
				i -= 1
				while B[i] == 0:
					i += 1
					ans += 1
				B[i] -= 1
				b = 0
				c = 0
			if ok == 1:
				break


table = {1 << i: i for i in range(64)}
for _ in range(int(input())):
	(big, n) = map(int, input().split())
	pows = list(map(int, input().split()))
	bits = [0] * 65
	for p in pows:
		bits[table[p]] += 1
	ans = 0
	for i in range(64):
		bits[i] += bits[i - 1] // 2
		if big % 2:
			if bits[i] > 0:
				bits[i] -= 1
			else:
				for j in range(i, 64):
					if bits[j] != 0:
						bits[j] -= 1
						for k in range(j - 1, i - 1, -1):
							bits[k] += 1
							ans += 1
						break
				if j == 63:
					ans = -1
					break
		big //= 2
	print(ans)


def solve(n, A):
	cnt = [0] * 64
	for a in A:
		cnt[a.bit_length() - 1] += 1
	result = 0
	for i in range(n.bit_length()):
		if n >> i & 1:
			for j in range(i, 64):
				if cnt[j] > 0:
					break
			if cnt[j] == 0:
				print(-1)
				return
			cnt[j] -= 1
			result += j - i
			for j in range(i, j):
				cnt[j] += 1
		cnt[i + 1] += cnt[i] // 2
	print(result)

def main():
	t = int(input().strip())
	for _ in range(t):
		(n, m) = [int(s) for s in input().strip().split()]
		A = [int(s) for s in input().strip().split()]
		solve(n, A)
main()


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

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

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	if sum(l) < n:
		print(-1)
		continue
	l.sort()
	d = defaultdict(float)
	c = 1
	for i in range(60):
		d[c] = 0
		c *= 2
	for i in range(m):
		d[l[i]] += 1
	s = []
	c = 1
	ans = 0
	while n > 0:
		s.append(c * (n % 2))
		c *= 2
		n //= 2
	s.sort()
	s = set(s)
	if 0 in s:
		s.remove(0)
	c = 0
	for i in d:
		if i == 576460752303423488:
			break
		if i in s and d[i] < 1:
			ma = i
			r = c
			while d[i] < 1:
				if i == 576460752303423488:
					break
				i *= 2
				r += 1
			ans += r - c
			d[i] -= 1
			i = ma
			d[i] += pow(2, r - c) - 1
			d[2 * i] += d[i] / 2
		else:
			if i in s:
				d[i] -= 1
			d[2 * i] += d[i] / 2
			d[i] = 0
		c += 1
	print(ans)


import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
	(n, k) = nm()
	a = nl()
	if sum(a) < n:
		print(-1)
		return
	g = [0] * 80
	ans = 0
	for x in a:
		g[x.bit_length() - 1] += 1
	for i in range(64):
		if n & 1 << i:
			if not g[i]:
				for j in range(i + 1, 64):
					if g[j]:
						ans += j - i
						for u in range(i, j):
							g[u] += 1
						g[j] -= 1
						break
			g[i] -= 1
		g[i + 1] += g[i] // 2
	print(ans)
	return
T = ni()
for _ in range(T):
	solve()


from collections import defaultdict
import sys
input = sys.stdin.readline
from math import log2, ceil
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	dictt = defaultdict(int)
	ai = list(map(int, input().split()))
	ai.sort()
	for i in ai:
		dictt[log2(i)] += 1
	nb = bin(n)[2:].rjust(61, '0')[::-1]
	ans = 0
	for i in range(len(nb)):
		if nb[i] == '1':
			if dictt[i] >= 1:
				dictt[i] -= 1
				dictt[i + 1] += dictt[i] // 2
				dictt[i] -= dictt[i] // 2 * 2
			else:
				for ii in range(i + 1, 61):
					if dictt[ii]:
						dictt[ii] -= 1
						if i == ii - 1:
							dictt[i] += 2
						else:
							for iii in range(ii - 1, i - 1, -1):
								dictt[iii] += 1
						ans += ii - i
						break
				else:
					print(-1)
					break
		else:
			dictt[i + 1] += dictt[i] // 2
			dictt[i] -= 2 * (dictt[i] // 2)
	else:
		print(ans)


def power(x):
	ans = 0
	while x != 1:
		ans += 1
		x >>= 1
	return ans
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	cnt = [0] * 80
	for i in range(m):
		cnt[power(a[i])] += 1
	if sum(a) < n:
		print(-1)
	else:
		(ans, idx) = (0, 0)
		while idx < 60:
			if 1 << idx & n:
				for i in range(idx):
					cnt[i + 1] += cnt[i] // 2
					cnt[i] = cnt[i] & 1
				if cnt[idx]:
					n -= 1 << idx
					cnt[idx] -= 1
				else:
					j = idx + 1
					while not cnt[j] and j < 60:
						j += 1
					cnt[j] -= 1
					for ii in range(idx, j):
						ans += 1
						cnt[ii] += 1
					n -= 1 << idx
					cnt[idx] -= 1
			idx += 1
		print(ans)


import sys
import math
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	al = list(map(int, input().split()))
	if n > sum(al):
		print(-1)
		continue
	abits = [0] * 100
	for a in al:
		abits[int(math.log2(a))] += 1
	bits = [0] * 100
	idx = 0
	while n > 0:
		bits[idx] = n % 2
		n //= 2
		idx += 1
	ans = 0
	for i in range(100):
		abits[i] -= bits[i]
		if abits[i] > 1:
			abits[i + 1] += abits[i] // 2
		if abits[i] < 0:
			for j in range(i + 1, 100):
				ans += 1
				if abits[j] >= 1:
					abits[j] -= 1
					break
				abits[j] = 1
	print(ans)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

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

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

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 get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def solution(a, m, n):
	if sum(a) < n:
		return '-1'
	d = defaultdict(int)
	for x in a:
		d[x] += 1
	a = [list(x) for x in d.items()]
	d = defaultdict(list)
	for x in a:
		d[x[0]] = x
	heapify(a)
	total = 0
	n = list(reversed(bi(n)))
	for i in range(len(n)):
		p = 1 << i
		if n[i] == '0':
			if a[0][0] == p:
				(num, cnt) = heappop(a)
				cnt //= 2
				if cnt > 0:
					p = num * 2
					if d[p]:
						d[p][1] += cnt
					else:
						l1 = [p, cnt]
						heappush(a, l1)
						d[p] = l1
			continue
		l = heappop(a)
		(num, cnt) = l
		if num == p:
			cnt -= 1
			cnt = cnt // 2
			if cnt > 0:
				p = p * 2
				if d[p]:
					d[p][1] += cnt
				else:
					l1 = [p, cnt]
					heappush(a, l1)
					d[p] = l1
		else:
			l[1] -= 1
			if l[1] > 0:
				heappush(a, l)
			else:
				d[num] = []
			log_last = round(math.log2(num))
			num_splits = log_last - i
			total += num_splits
			for j in range(i + 1, log_last):
				pi = 1 << j
				if d[pi]:
					d[pi][1] += 1
				else:
					l1 = [pi, 1]
					heappush(a, l1)
	return total

def main():
	T = 1
	T = ri()
	for i in range(T):
		(n, m) = ria()
		a = ria()
		x = solution(a, m, n)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


from math import log2
for _ in range(int(input())):
	(n, m) = map(int, input().split(' '))
	l = list(map(int, input().split(' ')))
	if sum(l) < n:
		print(-1)
	elif sum(l) == n:
		print(0)
	else:
		a = list(map(int, list(reversed(list(bin(n)[2:]))) + ['0'] * (30 - len(bin(n)) + 2)))
		d = [0] * 30
		for i in l:
			d[round(log2(i))] += 1
		for i in range(30):
			if a[i]:
				d[i] -= 1
		ans = 0
		if d.count(-1) == 0:
			print(0)
		else:
			for i in range(29):
				if d[i] <= -1:
					d[i + 1] -= 1
					ans += 1
					d[i] = 0
				else:
					d[i + 1] += d[i] // 2
					d[i] = d[i] % 2
			print(ans)


t = int(input())

def az(i):
	j = i
	while j > -1:
		if ab[j] != 0:
			return j
		j -= 1
	return j
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	nb = [0 for i in range(60)]
	ab = [0 for i in range(60)]
	i = 59
	while n > 0:
		nb[i] = n % 2
		i -= 1
		n >>= 1
	for j in a:
		k = 0
		while 1 << k != j:
			k += 1
		ab[59 - k] += 1
	ans = 0
	for i in range(59, -1, -1):
		if nb[i]:
			j = az(i)
			if ab[i] != 0:
				ab[i] -= 1
				ab[i - 1] += ab[i] // 2
			elif j != -1:
				ab[j] -= 1
				ans += i - j
				for k in range(j + 1, i + 1):
					ab[k] += 1
			else:
				print(-1)
				break
		else:
			ab[i - 1] += ab[i] // 2
	else:
		print(ans)


from collections import deque
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	a.sort()
	if n > sum(a):
		print(-1)
		continue
	a = deque(a)
	ans = 0
	unused = 0
	i = 0
	while 1 << i <= n:
		if n & unused:
			tmp = n & unused
			n ^= tmp
			unused ^= tmp
			continue
		if n >> i & 1 == 0:
			i += 1
			continue
		x = a.popleft()
		if x == 1 << i:
			n ^= 1 << i
		elif x < 1 << i:
			unused += x
		else:
			a.appendleft(x // 2)
			a.appendleft(x // 2)
			ans += 1
	print(ans)


sz = 1
temp = 1
while temp <= 1e+18:
	sz += 1
	temp <<= 1

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, m) = [int(x) for x in input().split()]
		a = [int(x) for x in input().split()]
		if sum(a) < n:
			allans.append(-1)
		else:
			setBitCnts = [0 for _ in range(sz)]
			for x in a:
				for i in range(sz):
					if x & 1 << i > 0:
						setBitCnts[i] += 1
			ans = 0
			smallerBitSum = 0
			for i in range(sz):
				smallerBitSum += setBitCnts[i] * 2 ** i
				if n & 1 << i > 0:
					if smallerBitSum >= 1 << i:
						smallerBitSum -= 1 << i
					else:
						j = i
						while setBitCnts[j] == 0:
							j += 1
						while j > i:
							setBitCnts[j] -= 1
							setBitCnts[j - 1] += 2
							j -= 1
							ans += 1
						setBitCnts[j] -= 1
			allans.append(ans)
	for x in allans:
		print(x)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(*args):
	assert len(args) >= 2, 'makeArr args should be (default value, dimension 1, dimension 2,...'
	if len(args) == 2:
		return [args[0] for _ in range(args[1])]
	else:
		return [makeArr(args[0], *args[2:]) for _ in range(args[1])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


from math import log
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lis = sorted(map(int, input().split()))
	s = sum(lis)
	if n > s:
		print('-1')
		continue
	d = [0] * 62
	for i in lis:
		d[int(log(i, 2))] += 1
	flag = True
	ans = 0
	for i in range(61):
		if n >> i & 1:
			if d[i]:
				d[i] -= 1
			else:
				f = -1
				for j in range(i + 1, 61):
					if d[j]:
						d[j] -= 1
						f = j
						break
				ans += j - i
				if f == -1:
					flag = False
					break
				for j in range(i, f):
					d[j] += 1
		d[i + 1] += d[i] // 2
	if flag:
		print(ans)
	else:
		print(-1)


import sys
input = sys.stdin.readline
TWO = {1 << i: i for i in range(64)}
t = int(input())
for tests in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	if sum(A) < n:
		print(-1)
		continue
	SUM = [0] * 64
	for b in range(64):
		if 1 << b & n != 0:
			SUM[b] = 1
	C = [0] * 64
	for a in A:
		C[TWO[a]] += 1
	ANS = 0
	for i in range(64):
		if SUM[i] > C[i]:
			for j in range(i + 1, 64):
				if C[j] > 0:
					break
			ANS += j - i
			C[i] += 1
			C[j] -= 1
			for k in range(i, j):
				C[k] += 1
		if C[i] > SUM[i]:
			x = (C[i] - SUM[i]) // 2
			C[i] -= 2 * x
			C[i + 1] += x
	print(ANS)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [int(item) for item in input().split()]
	if sum(a) < n:
		print(-1)
		continue
	comp = dict()
	for i in range(65):
		comp[2 ** i] = i
	nums = [0] * 65
	for item in a:
		nums[comp[item]] += 1
	filled = [False] * 65
	target = 0
	cumsum = 0
	ans = 0
	for i in range(65):
		cumsum += nums[i] * 2 ** i
		if n & 1 << i:
			target += 2 ** i
			if target <= cumsum:
				continue
			if filled[i]:
				continue
			r = i
			while nums[r] == 0:
				r += 1
			nums[r] -= 1
			cumsum += 2 ** r
			ans += r - i
			for j in range(i, r):
				filled[j] = True
	print(ans)


import math
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	if sum(a) < n:
		print(-1)
		continue
	bitarr = [0] * 60
	for x in a:
		bitarr[int(math.log2(x))] += 1
	n = bin(n)[2:]
	i = len(n) - 1
	j = 0
	val = 0
	while i >= 0:
		if n[i] == '0':
			bitarr[j + 1] += bitarr[j] // 2
			bitarr[j] %= 2
			j += 1
		elif n[i] == '1' and bitarr[j] >= 1:
			bitarr[j] -= 1
			bitarr[j + 1] += bitarr[j] // 2
			bitarr[j] %= 2
			j += 1
		else:
			temp = j + 1
			while 1:
				if bitarr[temp] >= 1:
					break
				else:
					temp += 1
			val += temp - j
			bitarr[temp] -= 1
			temp -= 1
			while temp != j:
				bitarr[temp] += 1
				temp -= 1
			bitarr[j] += 2
			bitarr[j] -= 1
			bitarr[j + 1] += bitarr[j] // 2
			bitarr[j] %= 2
			j += 1
		i -= 1
	print(val)


from collections import *
from sys import *
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	c = Counter(map(int, input().split()))
	s = bin(n)[2:][::-1].ljust(65, '0')
	(extra, least) = (0, 69)
	ans = 0
	for i in range(65):
		val = 1 << i
		if s[i] == '1':
			if c[val]:
				c[val] -= 1
			elif extra >= val:
				extra -= val
			else:
				least = min(least, i)
		if least < i and c[val]:
			ans += i - least
			c[val] -= 1
			least = 69
		extra += val * c[val]
	print(ans if least == 69 else -1)


import sys
input = sys.stdin.readline
from collections import Counter
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if sum(a) < n:
		print(-1)
		continue
	c = Counter(a)
	ans = 0
	for i in range(65):
		if n & 1 << i:
			if c[1 << i]:
				c[1 << i] -= 1
			else:
				for j in range(i + 1, 65):
					if c[1 << j]:
						c[1 << j] -= 1
						for k in range(i, j):
							c[1 << k] += 1
							ans += 1
						break
		c[1 << i + 1] += c[1 << i] // 2
		c[1 << i] %= 2
	print(ans)


t = int(input())
for _ in range(0, t):
	(n, m) = map(int, input().split())
	aa = [int(i) for i in input().split()]
	bits = [0] * 70
	for i in aa:
		bb = bin(i)[2:][::-1]
		for j in range(0, len(bb)):
			bits[j] += int(bb[j])
	ss = 0
	ans = [0] * 70
	bb = bin(n)[2:][::-1]
	for j in range(0, len(bb)):
		ans[j] += int(bb[j])
	(i, j) = (0, 0)
	while i < 64:
		if ans[i] == 0:
			bits[i + 1] += bits[i] // 2
			i += 1
		if ans[i] == 1 and bits[i]:
			bits[i] -= 1
			bits[i + 1] += bits[i] // 2
			i += 1
		elif ans[i] == 1 and (not bits[i]):
			j = i
			while j < 64 and bits[j] == 0:
				j += 1
			if j == 64:
				ss = -1
				break
			bits[j] -= 1
			ss += j - i
			i = j
	print(ss)


import sys
from collections import defaultdict

def get(dic, tar, b):
	s = bin(tar)
	n = len(s)
	num = 1 << n - 2
	ans = 0
	temp = defaultdict(int)
	for i in range(n - 1, 1, -1):
		if s[i] == '1':
			num = 1 << n - i - 1
			if dic[num] != 0:
				dic[num] -= 1
			else:
				for j in dic:
					temp[j] = dic[j]
				rem = 1 << n - i - 1
				num = 1 << n - i - 1
				while rem > 0 and num > 0:
					if dic[num] != 0:
						x = rem // num
						if dic[num] >= x:
							dic[num] -= x
							rem = 0
						else:
							m = num * dic[num]
							rem -= m
							dic[num] = 0
							num = num // 2
					else:
						num = num // 2
				if rem != 0:
					count = 0
					for j in temp:
						dic[j] = temp[j]
					num = 1 << n - i - 1
					rem = 1 << n - i - 1
					while num < b + 1:
						if dic[num] != 0:
							dic[num] -= 1
							ans += count
							num = num // 2
							while num >= rem:
								dic[num] += 1
								num = num // 2
							break
						else:
							num = num * 2
							count += 1
					if num >= b + 1:
						return -1
	return ans
t = int(sys.stdin.readline())
for _ in range(t):
	(tar, n) = map(int, sys.stdin.readline().split())
	arr = list(map(int, sys.stdin.readline().split()))
	dic = defaultdict(int)
	for i in arr:
		dic[i] += 1
	print(get(dic, tar, max(arr)))


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def creation(dict1, power, req):
	if power == 0:
		if dict1[2 ** power] >= req:
			return True
		else:
			return False
	elif power > 0:
		if dict1[2 ** power] >= req:
			return True
		else:
			return creation(dict1, power - 1, (req - dict1[2 ** power]) * 2)
for j in range(testcases):
	(n, m) = map(int, input().split())
	boxes = list(map(int, input().split()))
	boxes.sort()
	sum1 = 0
	ind1 = 0
	for s in range(len(boxes)):
		sum1 += boxes[s]
		if sum1 >= n:
			ind1 = s
			break
	if sum1 < n:
		print(-1)
	else:
		binrep = bin(n)[2:]
		nums = []
		divs = 0
		c = 0
		while 2 ** c < n:
			c += 1
		for s in range(len(binrep)):
			if binrep[s] == '1':
				nums.append(2 ** (len(binrep) - 1 - s))
		nums.reverse()
		dict1 = {}
		for s in range(ind1 + 1):
			val = boxes[s]
			if not val in dict1:
				dict1[val] = 1
			else:
				dict1[val] += 1
		newval = max(c + 1, int(math.log2(boxes[ind1]) + 1))
		for s in range(newval):
			val = 2 ** s
			if not val in dict1:
				dict1[val] = 0
		for s in range(len(nums)):
			val = nums[s]
			if creation(dict1, math.log2(val), 1) == True:
				req = 1
				power = math.log2(val)
				while req > 0:
					orig = req + 0
					req = (req - dict1[2 ** power]) * 2
					dict1[2 ** power] = max(0, dict1[2 ** power] - orig)
					power -= 1
			else:
				greater = boxes[bisect.bisect_right(boxes, val)]
				while val < greater:
					if dict1[greater] > 0:
						dict1[greater] -= 1
						greater = greater // 2
						dict1[greater] += 2
						divs += 1
					else:
						greater = greater // 2
				dict1[val] -= 1
		print(divs)


from collections import Counter

def go():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	total = sum(a)
	if total < n:
		return -1
	if total == n:
		return 0
	a = Counter((aa.bit_length() - 1 for aa in a))
	result = 0
	for i in range(n.bit_length()):
		if n & 1 << i:
			if a[i] > 0:
				a[i] -= 1
			else:
				j = i + 1
				while a[j] == 0:
					j += 1
				a[j] -= 1
				for k in range(i, j):
					a[k] += 1
				result += j - i
		a[i + 1] += a[i] // 2
	return result
t = int(input())
for _ in range(t):
	print(go())


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = map(int, input().split())
	bit = [0] * 100
	s = list(s)
	if sum(s) < n:
		print(-1)
		continue
	for x in s:
		bit[int.bit_length(x) - 1] += 1
	ans = 0
	pre = None
	now = n % 2
	for i in range(90):
		if now == 1:
			if bit[i] > 0:
				bit[i] -= 1
				if bit[i] > 0 and pre != None:
					ans += i - pre
					bit[i] -= 1
					pre = None
			elif pre == None:
				pre = i
		if now == 0:
			if bit[i] > 0 and pre != None:
				ans += i - pre
				bit[i] -= 1
				pre = None
		bit[i + 1] += bit[i] // 2
		n //= 2
		now = n % 2
	print(ans)


import sys
inp = sys.stdin.readline

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

def iin():
	return int(input())

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

def main():
	from math import log2 as lg
	T = iin()
	while T:
		T -= 1
		(n, m) = lin()
		a = lin()
		a1 = [0] * 61
		a2 = [0] * 61
		ch = n
		ch1 = 0
		while ch:
			if ch & 1:
				a2[ch1] = 1
			ch >>= 1
			ch1 += 1
		for i in a:
			a1[int(lg(i))] += 1
		ans = 0
		for i in range(61):
			if a2[i]:
				if a1[i]:
					a2[i] -= 1
					a1[i] -= 1
				else:
					for j in range(i):
						a1[j + 1] += a1[j] >> 1
						a1[j] = a1[j] & 1
					if a1[i]:
						a2[i] -= 1
						a1[i] -= 1
						continue
					for j in range(i + 1, 61):
						if a1[j]:
							ans += j - i
							break
					else:
						ans = -1
						break
					a2[i] -= 1
					for j in range(i, 61):
						if a1[j]:
							a1[j] -= 1
							break
						a1[j] += 1
		print(ans)
main()


for t in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	pows = [0] * 50
	for i in a:
		pows[i.bit_length() - 1] += 1
	p = 1
	i = 0
	tot = 0
	make = 100
	while (n > 0 or make < 100) and i < len(pows) - 1:
		if n % (2 * p) != 0:
			if pows[i] > 0:
				pows[i] -= 1
			else:
				make = min(make, i)
			n -= p
		if pows[i] > 0 and make < i:
			tot += i - make
			make = 100
			pows[i] -= 1
		pows[i + 1] += pows[i] // 2
		pows[i] %= 2
		i += 1
		p *= 2
	if n == 0 and make == 100:
		print(tot)
	else:
		print(-1)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def solve():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if sum(a) < n:
		print(-1)
		return
	k = 62
	count = [0] * k
	for ai in a:
		count[ai.bit_length() - 1] += 1
	ans = 0
	for i in range(k - 1):
		if n >> i & 1:
			if not count[i]:
				for j in range(i + 1, k):
					if count[j]:
						ans += j - i
						count[j] -= 1
						for l in range(j - 1, i - 1, -1):
							count[l] += 1
						count[i] += 1
						break
			count[i] -= 1
		count[i + 1] += count[i] // 2
	print(ans)
t = int(input())
for i in range(t):
	solve()


from math import log2

def run_case():
	(n, m) = map(int, input('').split(' '))
	cnt = [0] * 65
	s = 0
	for x in map(int, input('').split(' ')):
		cnt[int(log2(x))] += 1
		s += x
	if s < n:
		print(-1)
		return
	i = 0
	res = 0
	while i < 60:
		if 1 << i & n != 0:
			if cnt[i] > 0:
				cnt[i] -= 1
			else:
				while i < 60 and cnt[i] == 0:
					res += 1
					i += 1
				cnt[i] -= 1
				continue
		cnt[i + 1] += cnt[i] // 2
		i += 1
	print(res)
t = int(input(''))
for tc in range(t):
	run_case()


from math import log2, ceil
t = int(input())
MAX_N = 64
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if n > sum(a):
		print(-1)
		continue
	needs = [0 for _ in range(MAX_N)]
	bits = [0 for _ in range(MAX_N)]
	while n > 0:
		x = int(log2(n))
		n -= 2 ** x
		needs[x] += 1
	for i in range(m):
		bits[int(log2(a[i]))] += 1
	ans = 0
	for i in range(MAX_N - 1):
		if needs[i] > 0:
			for j in range(i, MAX_N - 1):
				if bits[j] > 0:
					bits[j] -= 1
					needs[i] = 0
					ans += j - i
					for k in range(i, j):
						bits[k] += 1
					break
		bits[i + 1] += bits[i] // 2
	print(ans)


from sys import stdin, stdout
from collections import Counter
t = int(stdin.readline().strip())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	alist = list(map(int, stdin.readline().split()))
	cnt = Counter(alist)
	mx = max(cnt.keys())
	(k, div) = (1, 0)
	while k <= n:
		if n & k:
			if cnt[k] == 0:
				j = k
				possible = False
				while j <= mx:
					if cnt[j] > 0:
						cnt[j] -= 1
						possible = True
						break
					cnt[j] += 1
					div += 1
					j *= 2
				if not possible:
					div = -1
					break
			cnt[k] -= 1
		cnt[k * 2] += cnt[k] // 2
		k *= 2
	stdout.write('{}\n'.format(div))


for _ in range(int(input())):
	(a, n) = map(int, input().split())
	ar = [int(x) for x in input().split()]
	ar.sort()
	b = bin(a).replace('0b', '')
	b = b[::-1]
	d = {}
	ans = 0
	sm = 0
	for i in ar:
		sm += i
		if i not in d:
			d[i] = 1
		else:
			d[i] += 1
	bl = False
	if sm < a:
		bl = True
	if bl == False:
		for i in range(len(b)):
			if b[i] == '0':
				if 2 ** i in d:
					if 2 ** (i + 1) in d:
						d[2 ** (i + 1)] += d[2 ** i] // 2
					else:
						d[2 ** (i + 1)] = d[2 ** i] // 2
			elif 2 ** i in d and d[2 ** i] > 0:
				d[2 ** i] -= 1
				if 2 ** (i + 1) in d:
					d[2 ** (i + 1)] += d[2 ** i] // 2
				else:
					d[2 ** (i + 1)] = d[2 ** i] // 2
			else:
				j = i + 1
				while 2 ** j not in d:
					j += 1
				val = 2 ** j
				d[val] -= 1
				while val != 2 ** i:
					val = val // 2
					ans += 1
					if val in d:
						d[val] += 1
					else:
						d[val] = 1
		print(ans)
	else:
		print('-1')


import sys
from heapq import heapify, heappop, heappush
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	total = sum(a)
	if total < n:
		print(-1)
		continue
	heapify(a)
	n_list = []
	shift = 0
	while n > 0:
		if n & 1:
			n_list.append(1 << shift)
		shift += 1
		n >>= 1
	ctr = 0
	for add in n_list:
		curr = 0
		while a:
			box = heappop(a)
			if box <= add:
				curr += box
				if curr >= add:
					break
			else:
				while box > add:
					box >>= 1
					ctr += 1
					heappush(a, box)
	print(ctr)


from math import log2

def cal(a):
	b = [0] * 61
	for j in a:
		b[int(log2(j))] += 1
	return b
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	if sum(a) < n:
		print(-1)
		continue
	a = cal(a)
	(i, l) = (0, 0)
	while i < 60:
		if 1 << i & n != 0:
			if a[i] == 0:
				while i < 60 and a[i] == 0:
					i += 1
					l += 1
				a[i] -= 1
				continue
			else:
				a[i] -= 1
		a[i + 1] += a[i] // 2
		i += 1
	print(l)


import heapq
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	heapq.heapify(a)
	f = True
	ans = 0
	if sum(a) < n:
		print(-1)
		continue
	for i in range(30):
		if n & 1 << i > 0:
			catch = 0
			while a and a[0] < 1 << i:
				catch += heapq.heappop(a)
				if catch == 1 << i:
					break
			if catch == 1 << i:
				continue
			if not a:
				f = False
				break
			rmv = heapq.heappop(a)
			while rmv != 1 << i:
				rmv //= 2
				ans += 1
				heapq.heappush(a, rmv)
		ct = 0
		while a and a[0] == 1 << i:
			ct += 1
			heapq.heappop(a)
		ct //= 2
		a = a + [1 << i + 1 for _ in range(ct)]
		heapq.heapify(a)
		if not f:
			break
	if f:
		print(ans)
	else:
		print(-1)


import math
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	l = [int(i) for i in input().split()]
	if sum(l) < n:
		print(-1)
	else:
		bina = [0] * 61
		for i in l:
			bina[int(math.log(i, 2))] += 1
		j = 0
		foo = 0
		while j < 60:
			if 1 << j & n != 0:
				if bina[j] > 0:
					bina[j] -= 1
				else:
					while j < 60 and bina[j] == 0:
						foo += 1
						j += 1
					bina[j] -= 1
					continue
			bina[j + 1] += bina[j] // 2
			j += 1
		print(foo)


import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List

def solve(N, A):
	if sum(A) < N:
		return -1
	nb = 64
	needs = [0 for _ in range(nb)]
	for i in range(nb):
		if N & 1 << i:
			needs[i] = 1
	have = [0 for _ in range(65)]
	for a in A:
		b = 0
		while a > 0:
			a >>= 1
			b += 1
		have[b - 1] += 1
	ans = 0
	for i in range(nb):
		if have[i] >= needs[i]:
			have[i] -= needs[i]
			have[i + 1] += have[i] // 2
		else:
			for j in range(i + 1, 64):
				if have[j] > 0:
					have[j] -= 1
					for k in range(i, j):
						have[k] += 1
					ans += j - i
					needs[i] = 0
					break
			if needs[i] > 0:
				return -1
	return ans
T = int(input())
for ti in range(T):
	(N, M) = map(int, input().split())
	A = [int(x) for x in input().split()]
	print(solve(N, A))


def solution():
	from sys import stdin, stdout
	from collections import defaultdict
	(_input, _print, _range, _int, _len, _str) = (stdin.readline, stdout.write, range, int, len, str)
	(_set, _enumerate, _reversed, _list, _sorted) = (set, enumerate, reversed, list, sorted)
	help_arr = [2 ** i for i in _range(30)]
	help_dict = {help_arr[i]: i for i in _range(30)}
	for _ in _range(_int(_input())):
		(length, n) = [_int(i) for i in _input().split()]
		arr = defaultdict(_int)
		summary = 0
		for i in _input().replace('\n', '').split():
			arr[help_dict[_int(i)]] += 1
			summary += _int(i)
		if summary < _int(length):
			_print('-1\n')
			continue
		bag = _set()
		_add_bag = bag.add
		for (i, v) in _enumerate(_reversed(_sorted(help_arr))):
			while v <= length:
				length %= v
				_add_bag(29 - i)
		summary = 0
		main_f = True
		for i in _sorted(_list(bag)):
			if i in arr and arr[i] > 0:
				arr[i] -= 1
				continue
			else:
				for j in _range(0, i):
					arr[j + 1] += arr[j] // 2
					arr[j] %= 2
				if i in arr and arr[i] > 0:
					arr[i] -= 1
					continue
				else:
					temp = i + 1
					f = False
					while temp < 30:
						if temp in arr and arr[temp] > 0:
							f = True
							break
						temp += 1
					if f:
						for j in _range(temp, i, -1):
							arr[j - 1] = arr[j] * 2
							arr[j] = 0
							summary += 1
						arr[i] -= 1
					else:
						main_f = False
						break
		if main_f:
			_print(_str(summary) + '\n')
		else:
			_print('-1\n')
solution()


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

def main():
	for case in range(int(input())):
		(n, m) = [int(x) for x in input().split()]
		boxes = [int(x) for x in input().split()]
		boxes.sort(reverse=True)
		divs = 0
		rem_sum = [x for x in boxes]
		rem_sum.append(0)
		for i in range(m - 1, -1, -1):
			rem_sum[i] += rem_sum[i + 1]
		for i in range(m):
			box = boxes[i]
			if box <= n:
				n -= box
			elif rem_sum[i + 1] >= n:
				pass
			else:
				while rem_sum[i + 1] < n:
					while box > n:
						box //= 2
						divs += 1
					n -= box
			if n == 0:
				break
		if n != 0:
			print(-1)
		else:
			print(divs)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

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

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

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

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

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

class IOWrapper(IOBase):

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


from math import log2
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	sm = 0
	ar = [0] * 64
	for e in list(map(int, input().split())):
		ar[int(log2(e))] += 1
		sm += e
	if sm < n:
		print(-1)
		continue
	(p, ans) = (0, 0)
	while p < 60:
		if n & 1 << p:
			if ar[p]:
				ar[p] -= 1
			else:
				while not ar[p] and p < 60:
					p += 1
					ans += 1
				ar[p] -= 1
				continue
		ar[p + 1] += ar[p] // 2
		p += 1
	print(ans)


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

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		if sum(a) < n:
			print(-1)
			continue
		(x, a, y, j, ans) = (Counter(a), sorted(set(a)), 1, 0, 0)
		while y <= n:
			if n & y:
				if x[y]:
					x[y] -= 1
					x[y << 1] += x[y] // 2
				else:
					while not (j == len(a) or (a[j] >= y and x[a[j]])):
						j += 1
					xx = a[j]
					x[xx] -= 1
					while xx != y:
						xx >>= 1
						x[xx] += 1
						ans += 1
					x[y] -= 1
			elif x[y]:
				x[y << 1] += x[y] // 2
			y <<= 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()


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 10 ** 9 + 7

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

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

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

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	(n, m) = li()
	l = sorted(li())
	if sum(l) < n:
		print(-1)
		continue
	if sum(l) == n:
		print(0)
		continue
	requirementarray = [n >> i & 1 for i in range(70)]
	wehave = [0] * 70
	for i in l:
		for j in range(70):
			wehave[j] += i >> j & 1
	tot = 0
	for i in range(69):
		if requirementarray[i] > wehave[i]:
			j = i + 1
			while j < 70 and (not wehave[j]):
				j += 1
			tot += j - i
			wehave[j] -= 1
			wehave[i] += 1
			for k in range(i, j):
				wehave[k] += 1
		else:
			temp = wehave[i] - requirementarray[i]
			wehave[i] -= temp
			wehave[i + 1] += temp // 2
	print(tot)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
from math import log2
for _ in range(int(input()) if True else 1):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	if sum(a) < n:
		print(-1)
		continue
	bits = [int(k) for k in list(binary(n, 64)[::-1])]
	powers = [0] * 64
	for each in a:
		powers[int(log2(each))] += 1
	ans = 0
	for i in range(63):
		if powers[i] and bits[i]:
			powers[i] -= 1
			bits[i] = 0
			powers[i + 1] += powers[i] // 2
			powers[i] = powers[i] % 2
		elif not bits[i]:
			powers[i + 1] += powers[i] // 2
			powers[i] = powers[i] % 2
		else:
			powers[i] += 2
			for j in range(i + 1, 64):
				if powers[j]:
					ans += j - i
					powers[j] -= 1
					break
				else:
					powers[j] += 1
	print(ans)


import sys
from math import *
input = sys.stdin.readline

def bo(i):
	return ord(i) - ord('a')
t = int(input())
w = t
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	lol = n
	a = [int(x) for x in input().split()]
	if n > sum(a):
		print(-1)
		continue
	p = bin(n)[2:]
	p = (len(bin(max(a))[2:]) - len(p)) * '0' + p
	q = list(len(p) * '0')
	f = [0 for i in range(len(q))]
	for i in range(m):
		x = int(log(a[i], 2))
		f[len(q) - x - 1] += 1
		q[len(q) - x - 1] = '1'
	g = [0 for i in range(len(q))]
	p = list(p)
	c = 0
	for i in range(len(q)):
		if i == 0:
			g[0] = f[len(f) - i - 1]
		else:
			g[i] = g[i - 1] + 2 ** i * f[len(f) - i - 1]
	n = len(f)
	g = g[::-1]
	r = 0
	for i in range(len(q) - 1, -1, -1):
		if p[i] == '1':
			lp = 0
			jk = 0
			h = [0 for i in range(n)]
			if True:
				if f[i] > 0:
					f[i] -= 1
					p[i] = '0'
					continue
				for j in range(i + 1, n):
					df = lp
					lp += min((2 ** (n - i - 1) - df) // 2 ** (n - j - 1), f[j]) * 2 ** (n - j - 1)
					h[j] = min((2 ** (n - i - 1) - df) // 2 ** (n - j - 1), f[j])
					if lp >= 2 ** (n - i - 1):
						jk = 1
						break
				if jk == 1:
					p[i] = '0'
					c += 2 ** (n - i - 1)
					for ii in range(n):
						f[ii] -= h[ii]
			if p[i] == '1':
				for j in range(i - 1, -1, -1):
					if f[j] > 0:
						r += i - j
						f[j] -= 1
						for k in range(j + 1, i):
							f[k] += 1
							q[k] = '1'
						f[i] += 1
						p[i] = '0'
						break
	prev = -9
	yu = 0
	for i in range(len(q)):
		if q[i] == '1' and f[i] > 0:
			prev = i
		if p[i] == '1' and prev == -9:
			yu = 1
			break
		elif p[i] == '1':
			r += -prev + i
			prev = i
	if yu == 1:
		print(-1)
	else:
		print(r)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

def iterative(f, stack=[]):

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

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

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

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

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

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

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

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

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

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

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

def solve():
	(n, m) = sep()
	ar = lis()
	c = counter(ar)
	d = defaultdict(int)
	if sum(ar) < n:
		print(-1)
		return
	for i in range(64):
		d[i] += c[1 << i]
	c = 0
	for i in range(64):
		if n & 1 << i == 0:
			if d[i] >= 0:
				d[i] -= 0
				d[i + 1] += d[i] // 2
			else:
				diff = 0 - d[i]
				d[i + 1] -= ceil(diff / 2)
				c += ceil(diff / 2)
			continue
		if d[i] >= 1:
			d[i] -= 1
			d[i + 1] += d[i] // 2
		else:
			diff = 1 - d[i]
			d[i + 1] -= ceil(diff / 2)
			c += ceil(diff / 2)
	print(c)
testcase(int(inp()))


import math
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	count_pow_2 = [0 for i in range(64)]
	nums = list(map(int, input().split()))
	for i in range(m):
		pow_2 = int(math.log(nums[i], 2))
		count_pow_2[pow_2] += 1
	b = bin(n)[2:]
	b = '0' * (64 - len(b)) + b
	b = b[::-1]
	idx = 0
	ans = 0
	possible = True
	while idx <= 63:
		if b[idx] == '0':
			if idx + 1 <= 63:
				count_pow_2[idx + 1] += count_pow_2[idx] // 2
			idx += 1
		elif count_pow_2[idx] >= 1:
			count_pow_2[idx] -= 1
			if idx + 1 <= 63:
				count_pow_2[idx + 1] += count_pow_2[idx] // 2
			idx += 1
		else:
			idx_2 = idx + 1
			if idx_2 > 63:
				possible = False
				break
			while idx_2 <= 63 and count_pow_2[idx_2] == 0:
				idx_2 += 1
			if idx_2 <= 63 and count_pow_2[idx_2] >= 1:
				count_pow_2[idx_2] -= 1
				ans += idx_2 - idx
				for i in range(idx, idx_2):
					count_pow_2[i] += 1
				idx = idx_2
			else:
				possible = False
				break
	print(ans if possible else -1)


import sys, math
import io, os
from collections import defaultdict as dd, deque, Counter

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

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(''.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
mod = int(1000000000.0) + 7
for i in range(int(data())):
	(n, m) = mdata()
	a = sorted(mdata())
	flag = True
	k = 0
	ans = 0
	for i in range(m):
		if n & k != 0:
			t = n & k
			n ^= t
			k ^= t
		if n & a[i] != 0:
			n ^= a[i]
		elif a[i] > n & -n and n & -n != 0:
			t = a[i] // 2
			cnt = 1
			c = 0
			while t:
				if n & t != 0:
					c = cnt
					n ^= t
				t //= 2
				cnt += 1
			ans += c
		else:
			k += a[i]
	if n & k != 0:
		t = n & k
		n ^= t
		k ^= n
	if n == 0:
		out(ans)
	else:
		out(-1)


import math

def min_div(number, listed):
	counts = [0 for i in range(60)]
	for i in listed:
		counts[int(math.log(i, 2))] += 1
	num_listed = [int(i) for i in bin(number)[2:]]
	num_listed.reverse()
	running_sum = 0
	cost = 0
	for i in range(len(num_listed)):
		if num_listed[i] == 1:
			if counts[i] > 0:
				running_sum += (counts[i] - 1) * 2 ** i
			elif running_sum >= 2 ** i:
				running_sum -= 2 ** i
			else:
				take_index = -1
				for j in range(i, 60):
					if counts[j] > 0:
						take_index = j
						counts[take_index] -= 1
						break
				if take_index == -1:
					return -1
				running_sum += 2 ** take_index - 2 ** i
				cost += take_index - i
		else:
			running_sum += counts[i] * 2 ** i
	return cost
useless = int(input())
for i in range(useless):
	(number, length) = [int(i) for i in input().split()]
	numbers = [int(i) for i in input().split()]
	print(min_div(number, numbers))


from math import log2
for _ in range(int(input())):
	(m, n) = map(int, input().split())
	s = list(map(int, input().split()))
	c = [0] * 65
	if sum(s) < m:
		print(-1)
		continue
	for i in s:
		c[int(log2(i))] += 1
	b = bin(m)[2:].zfill(64)[::-1]
	ans = 0
	i = 0
	while i < 64:
		if b[i] == '0':
			c[i + 1] += c[i] // 2
			i += 1
		elif b[i] == '1' and c[i]:
			c[i] -= 1
			c[i + 1] += c[i] // 2
			i += 1
		else:
			j = i
			while j < 64 and c[j] == 0:
				j += 1
			c[j] -= 1
			ans += j - i
			i = j
	print(ans)


from math import log2

def solve():
	(n, m) = map(int, input().split())
	v = [0] * 61
	s = 0
	for x in map(int, input().split()):
		v[int(log2(x))] += 1
		s += x
	if s < n:
		print(-1)
		return
	(i, ans) = (0, 0)
	while i < 60:
		if 1 << i & n != 0:
			if v[i] > 0:
				v[i] -= 1
			else:
				while i < 60 and v[i] == 0:
					i += 1
					ans += 1
				v[i] -= 1
				continue
		v[i + 1] += v[i] // 2
		i += 1
	print(ans)
t = int(input())
while t > 0:
	solve()
	t -= 1