import os
### START FAST IO ###
os_input = os.read(0, int(1e7)).split()
os_input_pos = -1
answer_list = []
def read_s():
  global os_input_pos
  os_input_pos += 1
  return os_input[os_input_pos].decode()
def read_i():
  return int(read_s())
def write_s(v):
  answer_list.append(v)
def write_i(v):
  write_s(str(v))
def print_ans():
  os.write(1, "\n".join(answer_list).encode())
  os.write(1, "\n".encode())
#### END FAST IO ####

from itertools import groupby

T = read_i()
while T:
  T -= 1
  n = read_i()
  k = read_i()
  a = sorted([read_i() % k for i in range(n)])
  ans = max([k - rem + 1 + k * (len(list(g)) - 1) for rem, g in groupby(a) if rem != 0], default=0)
  write_i(ans)

print_ans()


import os
### START FAST IO ###
os_input = os.read(0, int(1e7)).split()
os_input_pos = -1
answer_list = []
def read_s():
  global os_input_pos
  os_input_pos += 1
  return os_input[os_input_pos].decode()
def read_i():
  return int(read_s())
def write_s(v):
  answer_list.append(v)
def write_i(v):
  write_s(str(v))
def print_ans():
  os.write(1, "\n".join(answer_list).encode())
  os.write(1, "\n".encode())
#### END FAST IO ####

from itertools import groupby

T = read_i()
while T:
  T -= 1
  n = read_i()
  k = read_i()
  write_i(
    max(
      [
        k - rem + 1 + k * (len(list(g)) - 1)
        for rem, g in groupby(
          sorted([read_i() % k for i in range(n)]))
        if rem != 0
      ],
      default = 0
    )
  )

print_ans()


import os
### START FAST IO ###
os_input = os.read(0, int(1e7)).split()
os_input_pos = -1
answer_list = []
def read_s():
  global os_input_pos
  os_input_pos += 1
  return os_input[os_input_pos].decode()
def read_i():
  return int(read_s())
def write_s(v):
  answer_list.append(v)
def write_i(v):
  write_s(str(v))
def print_ans():
  os.write(1, "\n".join(answer_list).encode())
  os.write(1, "\n".encode())
#### END FAST IO ####

from itertools import groupby

T = read_i()
while T:
  T -= 1
  n = read_i()
  k = read_i()
  ans = max(
    [
      k - rem + 1 + k * (len(list(g)) - 1)
      for rem, g in groupby(
        sorted([read_i() % k for i in range(n)]))
      if rem != 0
    ],
    default = 0
  )
  write_i(ans)

print_ans()


import os
### START FAST IO ###
os_input = os.read(0, int(1e7)).split()
os_input_pos = -1
answer_list = []
def read_s():
  global os_input_pos
  os_input_pos += 1
  return os_input[os_input_pos].decode()
def read_i():
  return int(read_s())
def write_s(v):
  answer_list.append(v)
def write_i(v):
  write_s(str(v))
def print_ans():
  os.write(1, "\n".join(answer_list).encode())
  os.write(1, "\n".encode())
#### END FAST IO ####

from itertools import groupby

T = read_i()
while T:
  T -= 1
  n = read_i()
  k = read_i()
  write_i(max([k - rem + 1 + k * (len(list(g)) - 1) for rem, g in groupby(sorted([read_i() % k for i in range(n)])) if rem != 0], default = 0))

print_ans()


from collections import Counter
for _ in range(int(input())):
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    c=list(map(lambda x:x%k,a))
    if c==[0 for i in range(n)]:
        print(0)
    else:
        d=Counter(c)
        q=d.most_common(1)[0][1]
        for i in range(1,k):
            if d[i]==q:
                ind=i
                break
        count=1+k*(q-1)
        count+=(k-ind)
        print(count)


from collections import Counter
for _ in range(int(input())):
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    c=list(map(lambda x:x%k,a))
    if len(set(c))==1 and c[0]==0:
        print(0)
    else:
        d=Counter(c)
        Q=d.most_common()
        if Q[0][0]==0:
            q=Q[1][1]
            i=1
        else:
            q=Q[0][1]
            i=0
        temp=[]
        while i<len(Q) and Q[i][1]==q:
            temp.append(Q[i][0])
            i+=1
        temp.sort()
        if temp[0]==0:
            ind=temp[1]
        else:
            ind=temp[0]
        count=1+k*(q-1)
        count+=(k-ind)
        print(count)


from collections import Counter
for _ in range(int(input())):
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    c=list(map(lambda x:x%k,a))
    if len(set(c))==1 and c[0]==0:
        print(0)
    else:
        d=Counter(c)
        Q=d.most_common()
        if Q[0][0]==0:
            q=Q[1][1]
            i=1
        else:
            q=Q[0][1]
            i=0
        temp=[]
        while Q[i][1]==q:
            temp.append(Q[i][0])
            i+=1
        ind=min(temp)

        count=1+k*(q-1)
        count+=(k-ind)
        print(count)


from collections import Counter
for _ in range(int(input())):
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    b=list(map(lambda x:x%k,a))
    c=[]
    for i in b:
        if i!=0:
            c.append(i)
    if len(c)==0:
        print(0)
    else:
        d=Counter(c)
        q=d.most_common(1)[0][1]
        for i in range(1,k):
            if d[i]==q:
                ind=i
                break
        count=1+k*(q-1)
        count+=(k-ind)
        print(count)


from collections import Counter
for _ in range(int(input())):
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    c=list(map(lambda x:x%k,a))
    if c==[0 for i in range(n)]:
        print(0)
    else:
        d=Counter(c)
        Q=d.most_common()
        if Q[0][0]==0:
            q=Q[1][1]
        else:
            q=Q[0][1]
        for i in range(1,k):
            if d[i]==q:
                ind=i
                break
        count=1+k*(q-1)
        count+=(k-ind)
        print(count)


from sys import stdin, stdout
import math,sys
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import bisect as bi
import heapq
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))

def main():
    try:
        n,k=In()
        l=list(In())
        rem=[]
        d={}
        o=0
        #para=[]
        for x in l:
            if x%k==0:
                o+=1
            temp=(math.ceil(x/k)*k)-x
            while d.get(temp,-1)!=-1:
                temp+=k
            d[temp]=1
            #para.append([x,temp])

        #print(para)
        if o==n:
            print(0)
        else:
            l1=[]
            for x in d:
                l1.append(x)
            #l1.sort()
            j=0
            q=0
            #print(l1)
            ans=0

            while j<n:
                ans+=1
                if d.get(q,-1)!=-1:
                    q+=1
                    j+=1

                else:
                    q+=1
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import bisect as bi
import heapq
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))

def main():
    try:
        n,k=In()
        l=list(In())
        rem=[]
        d={}
        o=0
        #para=[]
        for x in l:
            if x%k==0:
                o+=1
            temp=(math.ceil(x/k)*k)-x
            while d.get(temp,-1)!=-1:
                temp+=k
            d[temp]=1
            #para.append([x,temp])

        #print(para)
        if o==n:
            print(0)
        else:
            l1=[]
            for x in d:
                l1.append(x)
            #l1.sort()
            j=0
            q=0
            #print(l1)
            ans=0

            while j<n:
                ans+=1
                if d.get(q,-1)!=-1:
                    if q==0:
                        ans-=1
                    q+=1
                    j+=1

                else:
                    q+=1
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d
def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1
def main():
    try:
        n,k=In()
        l=list(In())
        rem=[]
        for x in range(n):
            z=math.ceil(l[x]/k)*k-l[x]
            if z:
                rem.append(z)
        if len(rem):
            rem.sort()
            i=0
            n1=len(rem)
            while i<n1:
                x=1
                q=1
                for j in range(i+1,n1):
                    if rem[j]!=rem[i]:
                        i=j
                        q=0
                        break
                    else:
                        rem[j]+=(k*x)
                        x+=1
                if q:
                    break
            rem.sort()
            ans=rem[0]+1
            j=rem[0]+1
            for x in range(1,n1):
                ans+=(rem[x]-(j))
                ans+=1
                j=(rem[x]+1)
            print(ans)
        else:
            print(0)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import bisect as bi
import heapq
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))

def main():
    try:
        n,k=In()
        l=list(In())
        rem=[]
        d={}
        o=0
        #para=[]
        for x in l:
            if x%k==0:
                o+=1
            else:
                temp=(math.ceil(x/k)*k)-x
                while d.get(temp,-1)!=-1:
                    temp+=k
                d[temp]=1
            #para.append([x,temp])

        #print(para)
        if o==n:
            print(0)
        else:
            l1=[]
            for x in d:
                l1.append(x)
            #l1.sort()
            j=0
            q=0
            #print(l1)
            ans=0

            while j<len(d):
                ans+=1
                if d.get(q,-1)!=-1:
                    q+=1
                    j+=1

                else:
                    q+=1
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import bisect as bi
import heapq
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))

def main():
    try:
        n,k=In()
        l=list(In())
        rem=[]
        d={}
        o=0
        #para=[]
        for x in l:
            if x%k==0:
                o+=1
            temp=(math.ceil(x/k)*k)-x
            while d.get(temp,-1)!=-1:
                temp+=k
            d[temp]=1
            #para.append([x,temp])

        #print(para)
        if o==n:
            print(0)
        else:
            l1=[]
            for x in d:
                l1.append(x)
            #l1.sort()
            j=0
            q=0
            #print(l1)
            ans=0

            while j<n:
                ans+=1
                if d.get(q,-1)!=-1:
                    q+=1
                    j+=1

                else:
                    q+=1
            if o>1:
                ans-=1
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import bisect as bi
import heapq
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))

def main():
    try:
        n,k=In()
        l=list(In())
        o=0
        rem=[]
        for x in l:
            if x%k==0:
                o+=1
                rem.append(0)
            else:
                if k>x:
                    rem.append(k-x)
                else:
                    rem.append(x%k)
        j=0
        n1=len(rem)
        z=[0]*n1
        if o==n:
            print(0)
        else:
            rem.sort()
            print(rem)
            ans=0
            while j<n1:
                temp=0
                last=-1
                for x in range(n1):
                    if z[x]==0 and temp<k:
                        if last==-1:
                            last=rem[x]
                            ans+=(rem[x]-temp)
                            ans+=1
                            temp=rem[x]+1
                            j+=1
                            z[x]=1
                        else:
                            if last!=rem[x]:
                                ans+=(rem[x]-temp)
                                ans+=1
                                temp=rem[x]+1
                                last=rem[x]
                                j+=1
                                z[x]=1
                ans+=(k-temp)
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d
def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1

def main():
    try:
        n,k=In()
        l=list(In())
        d={}
        t=[]
        s=set()
        for x in range(n):
            if l[x]%k!=0:
                if d.get(l[x],-1)!=-1:
                    z=math.ceil(l[x]/k)
                    p=(z*k)-l[x]
                    while (p  in s):
                        p+=k
                    t.append(p)
                    s.add(p)
                    d[l[x]]+=1
                else:
                    d[l[x]]=1
                    p=(math.ceil(l[x]/k)*k)-l[x]
                    while (p  in s):
                        p+=k
                    t.append(p)
                    s.add(p)
        t.sort()
        #print(t)
        if len(t):

            ans=t[0]+1
            j=t[0]+1
            for x in range(1,len(t)):
                ans+=(t[x]-(j))
                ans+=1
                j=(t[x]+1)
            print(ans)
        else:
            print(0)

    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys,math
from io import BytesIO, IOBase
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(input()))
def In():return(map(int,input().split()))
#complete the main function with number of test cases to complete
def main():
    try:
        n,k=In()
        l=list(In())
        rem=[]
        for x in range(n):
            z=math.ceil(l[x]/k)*k-l[x]
            if z:
                rem.append(z)
        if len(rem):
            rem.sort()
            i=0
            n1=len(rem)
            while i<n1:
                x=1
                q=1
                for j in range(i+1,n1):
                    if rem[j]!=rem[i]:
                        i=j
                        q=0
                        break
                    else:
                        rem[j]+=(k*x)
                        x+=1
                if q:
                    break
            rem.sort()
            ans=rem[0]+1
            j=rem[0]+1
            for x in range(1,n1):
                ans+=(rem[x]-(j))
                ans+=1
                j=(rem[x]+1)
            print(ans)
        else:
            print(0)
    except:
        pass

M = 998244353
P = 1000000007

# region fastio

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):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys,math
from io import BytesIO, IOBase
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(input()))
def In():return(map(int,input().split()))
#complete the main function with number of test cases to complete
def main():
    try:
        n,k=In()
        l=list(In())
        d={}
        t=[]
        s=set()
        for x in range(n):
            if l[x]%k!=0:
                if d.get(l[x],-1)!=-1:
                    z=math.ceil(l[x]/k)
                    p=(z*k)-l[x]
                    while (p in s):
                        p+=k
                    t.append(p)
                    s.add(p)
                    d[l[x]]+=1
                else:
                    d[l[x]]=1
                    p=(math.ceil(l[x]/k)*k)-l[x]
                    while (p in s):
                        p+=k
                    t.append(p)
                    s.add(p)
        t.sort()
        if len(t):
            ans=t[0]+1
            j=t[0]+1
            for x in range(1,len(t)):
                ans+=(t[x]-(j))
                ans+=1
                j=(t[x]+1)
            print(ans)
        else:
            print(0)
    except:
        pass

M = 998244353
P = 1000000007

# region fastio

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):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

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 main():
    t=int(input())
    for i in range(t):
        n,k=map(int,input().split())
        a=list(map(int,input().split()))
        m=[]
        for j in a:
            m.append(k-(j%k))
        sm=sorted([x for x in m if x!=k])
        d=collections.Counter(sm)
        sd=sorted(d.items(),key=lambda x: (x[1],x[0]))
        if len(sm)==0:
            print (0)
            continue
        key=sd[-1][0]
        # for key in d.keys():
        #     if d[key]>1:
        #         temp=key+(d[key]-1)*k
        #         if temp>mx:
        #             mx=temp
        print (key+(d[key]-1)*k+1)
if __name__ == "__main__":
    main()


# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

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 main():
    t=int(input())
    for i in range(t):
        n,k=map(int,input().split())
        a=list(map(int,input().split()))
        m=[]
        for j in a:
            m.append(k-(j%k))
        sm=sorted(m)
        if sm[0]==k:
            print (0)
            continue
        d=collections.Counter(sm)
        mx=sorted(d.items(),key=lambda x: x[0])[-1][0]
        f=False
        for key in d.keys():
            if d[key]>1:
                f=True
                temp=key+(d[key]-1)*k
                if temp>mx:
                    mx=temp
        if f:
            print (mx+1)
        else:
            print (mx)
        # key=set(d.keys())
        # ans,x=1,1
        # cnt=0
        # while cnt<len(sm):
        #     if x%k==0:
        #         if k in key and d[k]>0:
        #             d[k]-=1
        #             cnt+=1
        #     else:
        #         if (x%k) in key:
        #             if d[x%k]>0:
        #                 d[x%k]-=1
        #                 cnt+=1
        #     x+=1
        #     ans+=1
        # print (ans)
if __name__ == "__main__":
    main()


# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

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 main():
    t=int(input())
    for i in range(t):
        n,k=map(int,input().split())
        a=list(map(int,input().split()))
        m=[]
        for j in a:
            m.append(k-(j%k))
        sm=sorted([x for x in m if x!=k])
        d=collections.Counter(sm)
        sd=sorted(d.items(),key=lambda x: (x[1],x[0]))
        if len(sm)==0:
            print (0)
            continue
        mx=sd[-1][0]
        for key in d.keys():
            if d[key]>1:
                temp=key+(d[key]-1)*k
                if temp>mx:
                    mx=temp
        print (mx+1)
        # if f:
        #     print (mx+1)
        # else:
        #     print (mx)

        # key=set(d.keys())
        # ans,x=1,1
        # cnt=0
        # while cnt<len(sm):
        #     if x%k==0:
        #         if k in key and d[k]>0:
        #             d[k]-=1
        #             cnt+=1
        #     else:
        #         if (x%k) in key:
        #             if d[x%k]>0:
        #                 d[x%k]-=1
        #                 cnt+=1
        #     x+=1
        #     ans+=1
        # print (ans)
if __name__ == "__main__":
    main()


# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

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 main():
    t=int(input())
    for i in range(t):
        n,k=map(int,input().split())
        a=list(map(int,input().split()))
        m=[]
        for j in a:
            m.append(k-(j%k))
        sm=sorted(m)
        if sm[0]==k:
            print (0)
            continue
        d=collections.Counter(sm)
        mx=sorted(d.items(),key=lambda x: x[0])[-1][0]
        f=False
        for key in d.keys():
            if d[key]>1:
                if key!=k:
                    f=True
                    temp=key+(d[key]-1)*k
                    if temp>mx:
                        mx=temp
        if f:
            print (mx+1)
        else:
            print (mx)
        # key=set(d.keys())
        # ans,x=1,1
        # cnt=0
        # while cnt<len(sm):
        #     if x%k==0:
        #         if k in key and d[k]>0:
        #             d[k]-=1
        #             cnt+=1
        #     else:
        #         if (x%k) in key:
        #             if d[x%k]>0:
        #                 d[x%k]-=1
        #                 cnt+=1
        #     x+=1
        #     ans+=1
        # print (ans)
if __name__ == "__main__":
    main()


# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

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 main():
    t=int(input())
    for i in range(t):
        n,k=map(int,input().split())
        a=list(map(int,input().split()))
        m=[]
        for j in a:
            m.append(k-(j%k))
        sm=sorted([x for x in m if x!=k])
        # if sm[0]==k:
        #     print (0)
        #     continue
        d=collections.Counter(sm)
        sd=sorted(d.items(),key=lambda x: (x[1],x[0]))
        if len(sm)==0:
            print (0)
            continue
        mx=sd[-1][0]
        # if mx[1]==1:
        #     print (k)
        #     continue
        # if
        # f=False
        # for key in d.keys():
        #     if d[key]>1:
        #         if key!=k:
        #             f=True
        #             temp=key+(d[key]-1)*k
        #             if temp>mx:
        #                 mx=temp
        # if f:
        #     print (mx+1)
        # else:
        #     print (mx)
        key=set(d.keys())
        ans,x=1,1
        cnt=0
        while cnt<len(sm):
            if x%k==0:
                if k in key and d[k]>0:
                    d[k]-=1
                    cnt+=1
            else:
                if (x%k) in key:
                    if d[x%k]>0:
                        d[x%k]-=1
                        cnt+=1
            x+=1
            ans+=1
        print (ans)
if __name__ == "__main__":
    main()


# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

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 main():
    t=int(input())
    for i in range(t):
        n,k=map(int,input().split())
        a=list(map(int,input().split()))
        m=[]
        for j in a:
            m.append(k-(j%k))
        sm=sorted([x for x in m if x!=k])
        d=collections.Counter(sm)
        if len(sm)==0:
            print (0)
            continue
        # both loop and sort can ac
        # 1.
        # for key in d.keys():
        #     if d[key]>1:
        #         temp=key+(d[key]-1)*k
        #         if temp>mx:
        #             mx=temp

        # 2.
        sd=sorted(d.items(),key=lambda x: (x[1],x[0]))
        key=sd[-1][0]
        print (key+(d[key]-1)*k+1)
if __name__ == "__main__":
    main()


# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

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 main():
    t=int(input())
    for i in range(t):
        n,k=map(int,input().split())
        a=list(map(int,input().split()))
        m=[]
        for j in a:
            m.append(k-(j%k))
        sm=sorted(m)
        if sm[0]==k:
            print (0)
            continue
        d=collections.Counter(sm)
        mx=sorted(d.items(),key=lambda x: (x[1],x[0]))[-1][0]
        # if mx[1]==1:
        #     print (k)
        #     continue
        # if
        # f=False
        # for key in d.keys():
        #     if d[key]>1:
        #         if key!=k:
        #             f=True
        #             temp=key+(d[key]-1)*k
        #             if temp>mx:
        #                 mx=temp
        # if f:
        #     print (mx+1)
        # else:
        #     print (mx)
        key=set(d.keys())
        ans,x=1,1
        cnt=0
        if mx==k:
            cnt=d[mx]
        while cnt<len(sm):
            if x%k==0:
                if k in key and d[k]>0:
                    d[k]-=1
                    cnt+=1
            else:
                if (x%k) in key:
                    if d[x%k]>0:
                        d[x%k]-=1
                        cnt+=1
            x+=1
            ans+=1
        print (ans)
if __name__ == "__main__":
    main()


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

'''
4
2
)(
4
()()
8
())()()(
10
)))((((())
'''
from collections import defaultdict
for _ in range(int(input())):
    n,k=mi()
    a = list(mi())
    for i in range(n):
        a[i] = a[i]%k
    a.sort(reverse=True)
    seen = defaultdict(int)
    ans = 0
    ma = -1
    # print(a)
    lol = list(range(k))
    for i in range(n):
        if a[i]:
            t = k-a[i]
            t = lol[t]
            if seen[t]==1:
                t+=k
                lol[t%k]=t
            # print(t)
            ma = max(ma,t)
            seen[t]=1
    # print(seen)
    print( ma+1)


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

'''
4
2
)(
4
()()
8
())()()(
10
)))((((())
'''
from collections import defaultdict
for _ in range(int(input())):
    n,k=mi()
    a = list(mi())
    for i in range(n):
        a[i] = a[i]%k
    a.sort(reverse=True)
    seen = defaultdict(int)
    ans = 0
    ma = -1
    # print(a)
    lol = defaultdict(int)
    for i in range(n):
        if a[i]:
            t = k-a[i]
            if t>0 and lol[t]==0:
                lol[t] = t
            t = lol[t]
            if seen[t]==1:
                t+=k
                lol[t%k]=t
            # print(t)
            ma = max(ma,t)
            seen[t]=1
    # print(seen)
    print( ma+1)


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

'''
4
2
)(
4
()()
8
())()()(
10
)))((((())
'''
from collections import defaultdict
for _ in range(int(input())):
    n,k=mi()
    a = list(mi())
    for i in range(n):
        a[i] = a[i]%k
    a.sort(reverse=True)
    seen = defaultdict(int)
    ans = 0
    ma = -1
    # print(a)
    for i in range(n):
        if a[i]:
            t = k-a[i]
            while seen[t]==1:
                t+=k
            # print(t)
            ma = max(ma,t)
            seen[t]=1
    # print(seen)
    print('ans', ma+1)


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

'''
4
2
)(
4
()()
8
())()()(
10
)))((((())
'''
from collections import defaultdict
for _ in range(int(input())):
    n,k=mi()
    a = list(mi())
    for i in range(n):
        a[i] = a[i]%k
    a.sort(reverse=True)
    seen = defaultdict(int)
    ans = 0
    ma = -1
    # print(a)
    for i in range(n):
        if a[i]:
            t = k-a[i]
            while seen[t]==1:
                t+=k
            # print(t)
            ma = max(ma,t)
            seen[t]=1
    # print(seen)
    print(ma+1)


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

'''
4
2
)(
4
()()
8
())()()(
10
)))((((())
'''
from collections import defaultdict
for _ in range(int(input())):
    n,k=mi()
    a = list(mi())
    for i in range(n):
        a[i] = a[i]%k
    a.sort(reverse=True)
    seen = defaultdict(int)
    ans = 0
    ma = -1
    # print(a)
    lol = defaultdict(int)
    for i in range(k):
        lol[i]=i
    for i in range(n):
        if a[i]:
            t = k-a[i]
            t = lol[t]
            if seen[t]==1:
                t+=k
                lol[t%k]=t
            # print(t)
            ma = max(ma,t)
            seen[t]=1
    # print(seen)
    print( ma+1)


from sys import stdin,stdout

# stdin = open("input.txt","r")
# stdout = open("output.txt","w")

t = int(stdin.readline().strip())

for _ in range(t):
	n,k = stdin.readline().strip().split(' ')
	n,k = int(n),int(k)

	arr = list(map(int,stdin.readline().strip().split(' ')))

	d={}
	for i in arr:
		key = (k-(i%k))%k
		if key in d:
			d[key]+=1
		else:
			d[key]=1
	m=0;ind=0
	# print(d)
	for i in d:
		if i!=0:
			if d[i]>m:
				m=d[i];ind=i
			if d[i]==m:
				if i>ind:
					ind = i
	# print(m,ind)
	if m==0 and ind==0:
		ans=0
	else:
		ans=(m-1)*k + ind + 1
	stdout.write(str(ans)+"\n");


from sys import stdin,stdout

# stdin = open("input.txt","r")
# stdout = open("output.txt","w")

t = int(stdin.readline().strip())

for _ in range(t):
	n,k = stdin.readline().strip().split(' ')
	n,k = int(n),int(k)

	arr = list(map(int,stdin.readline().strip().split(' ')))

	d={}
	for i in arr:
		key = (k-(i%k))%k
		if key in d:
			d[key]+=1
		else:
			d[key]=1
	m=0;ind=0
	# print(d)
	for i in d:
		if i!=0:
			if d[i]>m:
				m=d[i];
			if d[i]==m:
				ind = i
	# print(m,ind)
	if m==0 and ind==0:
		ans=-1
	else:
		ans=(m-1)*k + ind + 1
	stdout.write(str(ans)+"\n");


from sys import stdin,stdout

# stdin = open("input.txt","r")
# stdout = open("output.txt","w")

t = int(stdin.readline().strip())

for _ in range(t):
	n,k = stdin.readline().strip().split(' ')
	n,k = int(n),int(k)

	arr = list(map(int,stdin.readline().strip().split(' ')))

	d={}
	for i in arr:
		key = (k-(i%k))%k
		if key in d:
			d[key]+=1
		else:
			d[key]=1
	m=0;ind=0
	# print(d)
	for i in d:
		if i!=0:
			if d[i]>m:
				m=d[i];
			if d[i]==m:
				if i>ind:
					ind = i
	# print(m,ind)
	if m==0 and ind==0:
		ans=0
	else:
		ans=(m-1)*k + ind + 1
	stdout.write(str(ans)+"\n");


from sys import stdin,stdout

# stdin = open("input.txt","r")
# stdout = open("output.txt","w")

t = int(stdin.readline().strip())

for _ in range(t):
	n,k = stdin.readline().strip().split(' ')
	n,k = int(n),int(k)

	arr = list(map(int,stdin.readline().strip().split(' ')))

	t1 = [0 for i in range(k)]
	m,ind=0,0
	for i in arr:
		if (k-i%k)%k!=0:
			t1[(k-i%k)%k]+=1
			if t1[(k-i%k)%k]>m:
				m=t1[(k-i%k)%k]
			if t1[(k-i%k)%k]==m and (k-i%k)%k>ind:
				ind=(k-i%k)%k
	print(t1)
	if m==0 and ind==0:
		stdout.write(str(0)+"\n")
	else:
		stdout.write(str((m-1)*k + ind + 1)+"\n")


from sys import stdin,stdout

# stdin = open("input.txt","r")
# stdout = open("output.txt","w")

t = int(stdin.readline().strip())

for _ in range(t):
	n,k = stdin.readline().strip().split(' ')
	n,k = int(n),int(k)

	arr = list(map(int,stdin.readline().strip().split(' ')))

	t1 = [0 for i in range(k)]
	m,ind=0,0
	for i in arr:
		if (k-i%k)%k!=0:
			t1[(k-i%k)%k]+=1
			if t1[(k-i%k)%k]>m:
				m=t1[(k-i%k)%k]
			if t1[(k-i%k)%k]==m and (k-i%k)%k>ind:
				ind=(k-i%k)%k
	# print(t1)
	if m==0 and ind==0:
		stdout.write(str(0)+"\n")
	else:
		stdout.write(str((max(0,m-1))*k + ind + 1)+"\n")


from sys import stdin,stdout

# stdin = open("input.txt","r")
# stdout = open("output.txt","w")

t = int(stdin.readline().strip())

for _ in range(t):
	n,k = stdin.readline().strip().split(' ')
	n,k = int(n),int(k)

	arr = list(map(int,stdin.readline().strip().split(' ')))

	t1 = [0 for i in range(k)]
	m,ind=0,0
	for i in arr:
		if (k-i%k)%k!=0:
			t1[(k-i%k)%k]+=1
			if t1[(k-i%k)%k]>m:
				m=t1[(k-i%k)%k]
			if t1[(k-i%k)%k]==m and (k-i%k)%k>ind:
				ind=(k-i%k)%k
	# print(t1)
	if m==0 and ind==0:
		stdout.write(str(0)+"\n")
	else:
		stdout.write(str((m-1)*k + ind + 1)+"\n")


# Python3 program for the above approach

# Function to find all the local maxima
# and minima in the given array arr[]

def findLocalMaximaMinima(n, arr):

    # Empty lists to store points of
    # local maxima and minima
    mx = []
    mn = []

    # Checking whether the first point is
    # local maxima or minima or neither
    if(arr[0] > arr[1]):
        mx.append(0)
    elif(arr[0] < arr[1]):
        mn.append(0)

    # Iterating over all points to check
    # local maxima and local minima
    for i in range(1, n-1):

        # Condition for local minima
        if(arr[i-1] > arr[i] < arr[i + 1]):
            mn.append(i)

        # Condition for local maxima
        elif(arr[i-1] < arr[i] > arr[i + 1]):
            mx.append(i)

    # Checking whether the last point is
    # local maxima or minima or neither
    if(arr[-1] > arr[-2]):
        mx.append(n-1)
    elif(arr[-1] < arr[-2]):
        mn.append(n-1)

    r=[None]*(len(mx)+len(mn))
    if len(mx)>len(mn) and len(mn)>0 and len(mx)>0:
        r[::2]=mx
        r[1::2]=mn
    elif len(mn)>=len(mx) and len(mn) > 0 and len(mx)>0:
        r[::2]=mn
        r[1::2]=mx

    ans_arr=[]
    for x in r:
        ans_arr.append(arr[x])
    #print(ans_arr)
    ans=0
    for i in range(len(r)-1):
        if ans_arr[i+1] > ans_arr[i]:
            ans+=ans_arr[i+1]-ans_arr[i]
    print(ans)

for _ in [0]*int(input()):
    n=int(input())
    arr=[int(b) for b in input().split()]
    arr = arr[::-1]

    findLocalMaximaMinima(n,arr)


t=int(input())
while t>0:
    t-=1
    n,x=map(int,input().split())
    arr=sorted([int(y)%x for y in input().split()])[::-1]
    mvs=0
    #print('x ' + str(x))
    #print(arr)

    while True:
        count=0
        cArr=[]
        y = 0
        flag = True
        for n in arr:
            if n != 0:
                flag = False
                if x-n >= y and y < x:
                    mvs += x-n-y+1
                    y += x-n-y+1
                    cArr.append(count)
                    #print('n ', n, ' y ',y,' mvs ',mvs)
            elif n==0:
                cArr.append(count)
            count+=1

        if flag == True:
            mvs-=remain
            print(mvs)
            break

        remain = x-y
        mvs += remain
        #print(' r ',remain,' mvs ', mvs)
        for c in cArr[::-1]:
            del arr[c]
        #print(arr)


for _ in [0]*int(input()):
    n,x=map(int,input().split())
    arr=[int(a) for a in input().split()]
    dic = [0]*x

    for i in arr:
        dic[i%x] += 1
    dic[0] = 0
    #print(dic)

    m = max(dic)
    k = dic.index(m)
    if k!=0:
        print((m-1)*x+(x-k+1))
    else:
        print(0)


for _ in [0]*int(input()):
    n,x=map(int,input().split())
    arr=[int(a) for a in input().split()]
    dic = [0]*x

    for i in arr:
        dic[i%x] += 1
    dic[0] = 0
    #print(dic)

    m = max(dic)
    k = dic.index(m)
    print((m-1)*x+(x-k+1))


def keywithmaxval(d):
    #print(d)
    v=list(d.values())
    k=list(d.keys())

    sudo=[]
    for i in d:
        sudo.append([d[i],i])
    sudo.sort()

    m = max(sudo)[0]

    for j in sudo:
        if j[0] == m:
            return [j[1],m]

for _ in [0]*int(input()):
    n,x=map(int,input().split())
    arr=[int(a) for a in input().split()]
    dic = {}
    for i in arr:
        if i%x not in dic:
            dic[i%x] = 1
        else:
            dic[i%x] += 1
    if 0 in dic:
        dic[0] = 0

    k,m = keywithmaxval(dic)

    #print(k,m)

    if k!=0:
        print((m-1)*x+(x-k+1))
    else:
        print(0)


for _ in [0]*int(input()):
    n,x=map(int,input().split())
    arr=[int(a) for a in input().split()]
    dic = [0]*x

    for i in arr:
        dic[i%x] += 1
    del dic[0]

    #print(dic)

    m = max(dic)
    k = dic.index(m)+1
    print((m-1)*x+(x-k+1))

    #dic of remainders of arr[i]%x, ans is -max_rem+(x)*whatever the max of the-
    #-remainder list is


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    lis.sort(reverse=True)
    d=dict()
    for i in lis:
        if i!=0:
            d[k-i]=d.get(k-i,0)+1
    n=sum(d.values())
    res=[]
    while len(res)!=n:
        for i in d:
            if d[i]>0:
                d[i]-=1
                res.append(i)
    x=res[0]+1
    for i in range(1,n):
        if (res[i]-res[i-1])<=0:
            x+=(k-(res[i-1]-res[i]))
        else:
            x+=(res[i]-res[i-1])

    print(x)


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    d=dict()
    for i in lis:
        if i!=0:
            d[k-i]=d.get(k-i,0)+1
    x=1
    c=1
    n=sum(d.values())
    while n>0:
        try:
            if d[x]>0:
                d[x]-=1
                n-=1
        except:
            pass
        x=(x+1)%k
        c+=1
    print(c)


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    d=defaultdict(int)
    for i in lis:
        if i!=0:
            d[k-i]+=1
    x=1
    c=1
    n=sum(d.values())
    while n>0:
        if d[x]>0:
            d[x%k]-=1
            n-=1
        x=(x+1)%k
        c+=1
    print(c)


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    d=defaultdict(int)
    for i in lis:
        if i!=0:
            d[k-i]+=1
    x=1
    n=sum(d.values())
    while n>0:
        if d[x%k]>0:
            d[x%k]-=1
            n-=1
        x+=1
    print(x)


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    d=dict()
    for i in lis:
        if i!=0:
            d[k-i]=d.get(k-i,0)+1
    x=1
    n=sum(d.values())
    while n:
        if x%k in d and d[x%k]>0:
            d[x%k]-=1
            n-=1
        x+=1
    print(x)


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    d=dict()
    for i in lis:
        if i!=0:
            d[k-i]=d.get(k-i,0)+1
    x=1
    while d:
        if x%k in d:
            d[x%k]-=1
            if d[x%k]==0:
                del d[x%k]
        x+=1
    print(x)


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    d=dict()
    for i in lis:
        if i!=0:
            d[k-i]=d.get(k-i,0)+1
    x=1
    n=sum(d.values())
    s=set(d.keys())
    while n:
        if x%k in s and d[x%k]>0:
            d[x%k]-=1
            if d[x%k]==0:
                s.remove(x%k)
            n-=1
        x+=1
    print(x)


from sys import stdin
from collections import defaultdict
input=stdin.readline

for _ in range(int(input())):
    n,k=map(int,input().split())
    lis=list(map(int,input().split()))
    for i in lis:
        if i%k!=0:
            break
    else:
        print(0)
        continue
    for i in range(n):
        lis[i]%=k
    d=defaultdict(int)
    for i in lis:
        if i!=0:
            d[k-i]+=1
    x=1
    c=1
    n=sum(d.values())
    while n>0:
        if x in d and d[x]>0:
            d[x]-=1
            n-=1
        x=(x+1)%k
        c+=1
    print(c)


import math
import heapq
for _ in range(int(input())):
    n,k=list(map(int,input().split()))
    arr=list(map(int,input().split()))

    minheap=[]
    x=0
    for i in range(n):
        if(arr[i]%k!=0):
            heapq.heappush(minheap,k-arr[i]%k)

    while(minheap):
        value=heapq.heappop(minheap)
        if(x>=value):
            heapq.heappush(minheap,value+k)
        elif(x<value):
            x=value

    if(x==0):
        print(0)
    else:
        print(x+1)


import math
import heapq
for _ in range(int(input())):
    n,k=list(map(int,input().split()))
    arr=list(map(int,input().split()))

    minheap=[]
    x=0
    for i in range(n):
        if(arr[i]%k!=0):
            minheap.append(k-arr[i]%k)
    if(len(minheap)>0):
        minheap.sort()
        start=minheap[0]
        end=0
        value=[]
        value.append(start)
        for i in range(1,len(minheap)):
            if(minheap[i]==minheap[i-1]):
                value.append(value[i-1]+k)
            else:
                start=minheap[i]
                value.append(start)
        print(max(value))
    else:
        print(0)


import math
import heapq
for _ in range(int(input())):
    n,k=list(map(int,input().split()))
    arr=list(map(int,input().split()))

    minheap=[]
    x=0
    for i in range(n):
        if(arr[i]%k!=0):
            minheap.append(k-arr[i]%k)
    if(len(minheap)>0):
        minheap.sort()
        start=minheap[0]
        end=0
        value=[]
        value.append(start)
        for i in range(1,len(minheap)):
            if(minheap[i]==minheap[i-1]):
                value.append(value[i-1]+k)
            else:
                start=minheap[i]
                value.append(start)
        print(max(value)+1)
    else:
        print(0)


t = int(input())

for i in range(t):
    n, k = map(int, input().split())
    a = [(k - x) % k for x in map(int, input().split())]
    a.sort()
    prev = a[0]
    max_v = a[0]
    max_c = 0
    cur_c = 1
    for x in a[1:]:
        if x == prev:
            cur_c += 1
        else:
            cur_c = 0
        if cur_c >= max_c and x % k != 0:
            max_c = cur_c
            max_v = x + 1
        prev = x
    print(k*max_c + max_v)


t = int(input())

for i in range(t):
    n, k = map(int, input().split())
    a = [(k - x) % k for x in map(int, input().split())]
    a.sort()
    prev = a[0]
    max_v = a[0]
    max_c = 1
    cur_c = 0
    for x in a[1:]:
        if x == prev:
            cur_c += 1
        else:
            cur_c = 0
        if cur_c >= max_c and x % k != 0:
            max_c = cur_c
            max_v = x + 1
        prev = x
    print(k*max_c + max_v)


t = int(input())

for i in range(t):
    n, k = map(int, input().split())
    a = [(k - x) % k for x in map(int, input().split())]
    a.sort()
    prev = a[0]
    max_v = a[0]
    max_c = 0
    cur_c = 0
    for x in a[1:]:
        if x == prev:
            cur_c += 1
        else:
            cur_c = 0
        if cur_c >= max_c and x % k != 0:
            max_c = cur_c
            max_v = x + 1
        prev = x
    print(k*max_c + max_v)


t = int(input())

for i in range(t):
    n, k = map(int, input().split())
    a = [(k - x) % k for x in map(int, input().split())]
    a.sort()
    prev = -1
    max_v = 0
    max_c = 0
    cur_c = 0
    for x in a:
        if x == prev:
            cur_c += 1
        else:
            cur_c = 0
        if cur_c >= max_c and x % k != 0:
            max_c = cur_c
            max_v = x + 1
        prev = x
    print(k*max_c + max_v)


import sys
import math
from math import *
from collections import defaultdict
import os
from io import BytesIO, IOBase
from collections import deque
def check(d):
	if list(d.keys()) == ['a','b','c']:
		if d['a'] == d['c'] or d['b'] == d['c']:
			return True
	return False

def main(d):

	n,k = list(map(int, input().split()))
	a = list(map(int , input().split()))
	d = defaultdict(lambda : 0)
	for	i in a:
		if i %k == 0:
			continue
		d[k-(i%k)] += 1
	c = 0
	x = -1
	mx = 0
	midx = 0
	if len(d.keys()) == 0:
		print(0)
		return
	for i,j in d.items():
		if j>=mx:
			mx = j

	for j in reversed(sorted(list(d.keys()))):
		if d[j] == mx:
			midx = j
			break
	print((k*(mx-1)) + midx + 1)

d = defaultdict(lambda:0)
for i in range(int(input())):
	main(d)


import sys
import math
from math import *
from collections import defaultdict
import os
from io import BytesIO, IOBase
from collections import deque
def check(d):
	if list(d.keys()) == ['a','b','c']:
		if d['a'] == d['c'] or d['b'] == d['c']:
			return True
	return False

def main(d):

	n,k = list(map(int, input().split()))
	a = list(map(int , input().split()))
	d = defaultdict(lambda : 0)
	for	i in a:
		if i %k == 0:
			continue
		d[k-(i%k)] += 1
	c = 0
	x = -1
	mx = 0
	midx = 0
	if len(d.keys()) == 0:
		print(0)
		return
	for i,j in d.items():
		if j>=mx:
			mx = j

		if mx == j and midx<i:
			midx = i

	print((k*(mx-1)) + midx + 1)

d = defaultdict(lambda:0)
for i in range(int(input())):
	main(d)


import sys
import math
from math import *
from collections import defaultdict
import os
from io import BytesIO, IOBase
from collections import deque
def check(d):
	if list(d.keys()) == ['a','b','c']:
		if d['a'] == d['c'] or d['b'] == d['c']:
			return True
	return False

def main(d):

	n,k = list(map(int, input().split()))
	a = list(map(int , input().split()))
	d = defaultdict(lambda : 0)
	for	i in a:
		if i %k == 0:
			continue
		d[k-(i%k)] += 1
	c = 0
	x = -1
	mx = 0
	midx = 0
	if len(d.keys()) == 0:
		print(0)
		return
	for i,j in d.items():
		if j>=mx:
			mx = j
			midx = i
		if mx == j and midx<i:
			midx = i

	print((k*(mx-1)) + midx + 1)

d = defaultdict(lambda:0)
for i in range(int(input())):
	main(d)


import sys
import math
from math import *
from collections import defaultdict
import os
from io import BytesIO, IOBase
from collections import deque
def check(d):
	if list(d.keys()) == ['a','b','c']:
		if d['a'] == d['c'] or d['b'] == d['c']:
			return True
	return False

def main(d):

	n,k = list(map(int, input().split()))
	a = list(map(int , input().split()))
	d = defaultdict(lambda : 0)
	for	i in a:
		if i %k == 0:
			continue
		d[k-(i%k)] += 1
	c = 0
	x = -1
	mx = 0
	midx = 0
	if len(d.keys()) == 0:
		print(0)
		return
	for i,j in d.items():
		if j>=mx:
			mx = j
			if midx < i:
				midx = i

	print((k*(mx-1)) + midx + 1)

sys.stdin = open("input","r")
sys.stdout = open("output","w")
d = defaultdict(lambda:0)
for i in range(int(input())):
	main(d)


import sys
import math
from math import *
from collections import defaultdict
import os
from io import BytesIO, IOBase
from collections import deque
def check(d):
	if list(d.keys()) == ['a','b','c']:
		if d['a'] == d['c'] or d['b'] == d['c']:
			return True
	return False

def main(d):

	n,k = list(map(int, input().split()))
	a = list(map(int , input().split()))
	d = defaultdict(lambda : 0)
	for	i in a:
		if i %k == 0:
			continue
		d[k-(i%k)] += 1
	c = 0
	x = -1
	mx = 0
	midx = 0
	if len(d.keys()) == 0:
		print(0)
		return
	for i,j in d.items():
		if j>=mx:
			mx = j
			if midx < i:
				midx = i

	print((k*(mx-1)) + midx + 1)

d = defaultdict(lambda:0)
for i in range(int(input())):
	main(d)


for _ in range(int(input())):
    n , k = map(int, input().split())
    a = [*map(int, input().split())]
    a = [k-(i%k) for i in a]
    ans,g = 0,{key:a.count(key) for key in set(a)}
    i,j = n - g.get(k,0), 0
    while i > 0:
        if g.get(j,0) >= 1:
            g[j]-=1
            i -= 1
        j = (j+1)%k
        ans += 1
    print(ans)


from collections import defaultdict
for _ in range(int(input())):
    n , k = map(int, input().split())
    a = [*map(int, input().split())]
    g = defaultdict(int)

    for i in a:
        if i%k:
            g[k-i%k]+=1
    print(max(i+k*(g[i]-1)+1 for i in g)if g else 0)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
    n , k = map(int, input().split())
    a = [*map(lambda x: k-(x%k) ,map(int, input().split()))]
    ans,g = 0,{key:a.count(key) for key in set(a)}
    i,j = n - g.get(k,0), 0
    while i > 0:
        if g.get(j,0) >= 1:
            g[j]-=1
            i -= 1
        j = (j+1)%k
        ans += 1
    print(ans)


test_case = int(input())
for _ in range(test_case):
    size, div = map(int, input().split())
    arr = list(map(int, input().split()))
    s = {arr[i]%div : 0 for i in range(size)}
    for i in a:
        if i% div:
            s[i%div] += 1
    x = 0
    for i in s.keys():
        x = max(x, s[i]*k-i)
    if x == 0:
        print(0)
    else:
        print(x+1)


test_case = int(input())
for _ in range(test_case):
    size, div = map(int, input().split())
    arr = list(map(int, input().split()))
    brr = []
    for i in arr:
        if i % div:
            brr.append((1 + i // div)*div)
        else:
            brr.append(i)
    #print(brr)
    for i in range(len(brr)):
        arr[i] = brr[i] - arr[i]
    arr.sort()
    count = 0
    #print(arr)
    while len(arr) and arr[-1] != 0:
        brr = list(set(arr))
        #print(arr)
        #print(brr)
        x = []
        p = 0
        for i in arr:
            if p < len(brr) and i == brr[p]:
                p += 1
            else:
                x.append(i)
        #print(x)
        for i in range(len(x)):
            x[i] += div
        if len(x):
            count = x[-1] + 1
        else:
            count = max(count, arr[-1]+1)

        arr = x.copy()
        #print(x)
    print(count)


test_case = int(input())
for _ in range(test_case):
    size, div = map(int, input().split())
    arr = list(map(int, input().split()))
    s = {arr[i]%div : 0 for i in range(size)}
    for i in arr:
        if i% div:
            s[i%div] += 1
    x = 0
    for i in s.keys():
        x = max(x, s[i]*k-i)
    if x == 0:
        print(0)
    else:
        print(x+1)


test_case = int(input())
for _ in range(test_case):
    size, div = map(int, input().split())
    arr = list(map(int, input().split()))
    s = {arr[i]%div : 0 for i in range(size)}
    for i in arr:
        if i% div:
            s[i%div] += 1
    x = 0
    for i in s.keys():
        x = max(x, s[i]*div-i)
    if x == 0:
        print(0)
    else:
        print(x+1)


test_case = int(input())
for _ in range(test_case):
    size, div = map(int, input().split())
    arr = list(map(int, input().split()))
    brr = []
    for i in arr:
        if i % div:
            brr.append((1 + i // div)*div)
        else:
            brr.append(i)
    #print(brr)
    for i in range(len(brr)):
        arr[i] = brr[i] - arr[i]
    arr.sort()
    count = 0
    #print(arr)
    while len(arr) and arr[-1] != 0:
        brr = list(set(arr))
        #print(arr)
        #print(brr)
        x = []
        p = 0
        for i in arr:
            if p < len(brr) and i == brr[p]:
                p += 1
            else:
                x.append(i)
        #print(x)
        for i in range(len(x)):
            x[i] += div
        if len(x):
            if x[-1] % div:
                count = x[-1] + 1
            else:
                count =  x[-1]
        else:
            count = max(count, arr[-1]+1)
        #print(count)
        if len(x) == 1:
            break
        arr = x.copy()
        #print(x)
    print(count)


test_case = int(input())
for _ in range(test_case):
    size, div = map(int, input().split())
    arr = list(map(int, input().split()))
    brr = []
    for i in arr:
        if i % div:
            brr.append( ((i // div)+1)*div - i)
        else:
            brr.append(0)
    brr.sort()
    x = list(set(brr))
    if brr[-1] == 0:
        print(0)
    else:
        y = []
        for i in x:
            y.append([i, brr.count(i)])
        count = 0
        #print(y)
        while count < len(y):
            if y[count][1] == 1:
                count += 1
            else:
                y.append([y[count][0]+div, y[count][1] - 1])
                count += 1

        print(y[count-1][0]+1)


#include <bits/stdc++.h>
using namespace std;
const int maxm = 400010;
const int maxn = 200100;
int n, m;
struct node {
    int u, v, next;
}edge[maxm];
int edgehead[maxn], tot;
int vis[maxn];
int ans[maxn], ans0[maxn];
int index, index0;

inline void init() {
    for (int i = 0; i < maxn; i++) {
        edgehead[i] = 0;
        vis[i] = 0;
    }
    tot = 1;
    index = 0;
    index0 = 0;
}
inline void addNode (int u, int v) {
    edge[tot].v = v;
    edge[tot].next = edgehead[u];
    edgehead[u] = tot++;
}

inline void dfs (int now, int val) {
     for (int i = edgehead[now]; i; i = edge[i].next) {
        int v = edge[i].v;
        if (vis[v]) continue;
        vis[v] = 1;
        if (val == 0) {
            ans[++index] = v;
        } else {
            ans0[++index0] = v;
        }
        dfs(v, val^1);
    }
}
int main() {
    int T; scanf("%d", &T);
    while (T--) {
        scanf("%d %d", &n, &m);
        init();
        for (int i = 1; i <= m; i++) {
            int u, v; scanf("%d%d", &u, &v);
            addNode (u, v);
            addNode (v, u);
        }
        vis[1] = 1;
        ans[++index] = 1;
        dfs(1, 1);
        if (index <= (n / 2)) {
            printf("%d\n", index);
            for (int i = 1; i <= index; i++) {
                printf("%d ", ans[i]);
            }
        } else {
            printf("%d\n", index0);
            for (int i = 1; i <= index0; i++) {
                printf("%d ", ans0[i]);
            }
        }
        printf("\n");
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxm = 500010;
const int maxn = 200100;
int n, m;
struct node {
    int u, v, next;
}edge[maxm];
int edgehead[maxn], tot;
int vis[maxn];
int ans[maxn], ans0[maxn];
int index, index0;

inline void init() {
    for (int i = 0; i <= n; i++) {
        edgehead[i] = 0;
        vis[i] = 0;
    }
    tot = 1;
    index = 0;
    index0 = 0;
}
inline void addNode (int u, int v) {
    edge[tot].v = v;
    edge[tot].next = edgehead[u];
    edgehead[u] = tot++;
}

inline void dfs (int now, int val) {
    if (val == 1) {
       ans[++index] = now;
    } else {
        ans0[++index0] = now;
    }
    for (int i = edgehead[now]; i; i = edge[i].next) {
        int v = edge[i].v;
        if (vis[v]) continue;
        vis[v] = 1;
        dfs(v, val^1);
    }
}
int main() {
    int T; scanf("%d", &T);
    while (T--) {
        scanf("%d %d", &n, &m);
        init();
        for (int i = 1; i <= m; i++) {
            int u, v; scanf("%d %d", &u, &v);
            addNode (u, v);
            addNode (v, u);
        }
        vis[1] = 1;
        dfs(1, 1);
        if (index <= index0) {
            printf("%d\n", index);
            for (int i = 1; i <= index; i++) {
                printf("%d ", ans[i]);
            }
        } else {
            printf("%d\n", index0);
            for (int i = 1; i <= index0; i++) {
                printf("%d ", ans0[i]);
            }
        }
        printf("\n");
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxm = 500100;
const int maxn = 200100;
int n, m;
struct node {
    int u, v, next;
}edge[maxm];
int edgehead[maxn], tot;
int vis[maxn], check[maxn];
int flag;
void init() {
    for (int i = 0; i <= n; i++) {
        edgehead[i] = 0;
        vis[i] = 0;
        check[i] = 0;
    }
    tot = 1;
    flag = 0;
}
void addNode (int u, int v) {
    edge[tot].v = v;
    edge[tot].next = edgehead[u];
    edgehead[u] = tot++;
}
void bfs (int point) {
    vector <int> ans, ans0;
    ans.push_back(point);
    vis[point] = 1;
    stack <int> Q;
    Q.push(point);
    check[point] = 1;
    while (!Q.empty()) {
        int now = Q.top();
        Q.pop();
        for (int i = edgehead[now]; i; i = edge[i].next) {
            int v = edge[i].v;
            if (vis[v]) continue;
            vis[v] = 1;
            Q.push(v);
            if (check[now] == 0) {
                check[v] = 1;
                ans.push_back(v);
            } else {
                ans0.push_back(v);
            }
        }
    }
    if (ans.size() <= (floor)(n / 2)) {
        cout << ans.size() << "\n";
        for (int i = 0; i < ans.size(); i++) {
            cout << ans[i] << " ";
        }
    }
    else {
        cout << ans0.size() << "\n";
        for (int i = 0; i < ans0.size(); i++) {
            cout << ans0[i] << " ";
        }
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T; cin >> T;
    while (T--) {
        cin >> n >> m;
        init();
        for (int i = 1; i <= m; i++) {
            int u, v, w; cin >> u >> v;
            addNode (u, v);
            addNode (v, u);
        }
        bfs(1);
        cout << "\n";
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxm = 500010;
const int maxn = 200100;
int n, m;
struct node {
    int u, v, next;
}edge[maxm];
int edgehead[maxn], tot;
int vis[maxn];
int ans[maxn], ans0[maxn];
int index, index0;

void init() {
    for (int i = 0; i < maxn; i++) {
        edgehead[i] = 0;
        vis[i] = 0;
    }
    tot = 1;
    index = 0;
    index0 = 0;
}
void addNode (int u, int v) {
    edge[tot].v = v;
    edge[tot].next = edgehead[u];
    edgehead[u] = tot++;
}

void dfs (int now, int val) {
     for (int i = edgehead[now]; i; i = edge[i].next) {
        int v = edge[i].v;
        if (vis[v]) continue;
        vis[v] = 1;
        if (val == 0) {
            ans[++index] = v;
        } else {
            ans0[++index0] = v;
        }
        dfs(v, val^1);
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T; cin >> T;
    while (T--) {
        cin >> n >> m;
        init();
        for (int i = 1; i <= m; i++) {
            int u, v, w; cin >> u >> v;
            addNode (u, v);
            addNode (v, u);
        }
        vis[1] = 1;
        ans[++index] = 1;
        dfs(1, 1);
        if (index <= (n / 2)) {
            cout << index << "\n";
            for (int i = 1; i <= index; i++) {
                cout << ans[i] << " ";
            }
        } else {
            cout << index0 << "\n";
            for (int i = 1; i <= index0; i++) {
                cout << ans0[i] << " ";
            }
        }
        cout << "\n";
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxm = 500100;
const int maxn = 200100;
int n, m;
struct node {
    int u, v, next;
}edge[maxm];
int edgehead[maxn], tot;
int vis[maxn], check[maxn];
int flag;
void init() {
    for (int i = 0; i <= n; i++) {
        edgehead[i] = 0;
        vis[i] = 0;
        check[i] = 0;
    }
    tot = 1;
    flag = 0;
}
void addNode (int u, int v) {
    edge[tot].v = v;
    edge[tot].next = edgehead[u];
    edgehead[u] = tot++;
}
void bfs (int point) {
    vector <int> ans, ans0;
    ans.push_back(point);
    vis[point] = 1;
    stack <int> Q;
    Q.push(point);
    check[point] = 1;
    while (!Q.empty()) {
        int now = Q.top();
        Q.pop();
        for (int i = edgehead[now]; i; i = edge[i].next) {
            int v = edge[i].v;
            if (vis[v]) continue;
            vis[v] = 1;
            Q.push(v);
            if (check[now] == 0) {
                check[v] = 1;
                ans.push_back(v);
            } else {
                ans0.push_back(v);
            }
        }
    }
    if (ans.size() <= (floor)(n / 2)) {
        cout << ans.size() << "\n";
        for (int i = 0; i < ans.size(); i++) {
            cout << ans[i] << " ";
        }
    }
    else {
        cout << ans0.size() << "\n";
        for (int i = 0; i < ans.size(); i++) {
            cout << ans0[i] << " ";
        }
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T; cin >> T;
    while (T--) {
        cin >> n >> m;
        init();
        for (int i = 1; i <= m; i++) {
            int u, v, w; cin >> u >> v;
            addNode (u, v);
            addNode (v, u);
        }
        bfs(1);
        cout << "\n";
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
vector <bool> mark;
vector <pair <int, int>> deg;
set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		deg.clear();
		adj.resize(n);
		deg.resize(n);
		mark.clear();
		mark.resize(n);
		for (int i = 0; i < n; i++)
			deg[i].second = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			deg[v].first ++;
			adj[u].push_back(v);
			deg[u].first ++;
		}
		for (int i = 0; i < n; i++)
			D.insert(deg[i]);
		int G = 0;
		ans.clear();
		while (G != n){
			pair <int, int> T = *(D.rbegin());
			G += 1 + T.first;
			ans.push_back(T.second);
			D.erase(T);
			mark[T.second] = true;
			for (auto v: adj[T.second]){
				for (auto u: adj[v]){
					if (!(mark[u] || mark[v])){
						D.erase(deg[u]);
						deg[u].first --;
						D.insert(deg[u]);
					}
				}
				mark[v] = true;
				D.erase(deg[v]);
			}
			// remove(T.second);
		}
		cout << ans.size() << '\n';
		for (auto d: ans)
			cout << d + 1 << ' ';
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
vector <bool> mark;
// vector <int> deg;
// set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		// deg.clear();
		adj.resize(n);
		// deg.resize(n);
		mark.clear();
		mark.resize(n, false);
		// D.clear();
		// for (int i = 0; i < n; i++)
			// deg[i].se/cond = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			// deg[v] ++;
			adj[u].push_back(v);
			// deg[u] ++;
		}
		// for (int i = 0; i < n; i++)
			// D.insert(deg[i]);
		// int G = 0;
		ans.clear();
		for (int i = 0; i < n; i++){
			if (!(mark[i])){
				ans.push_back(i);
				for (auto v: adj[i]){
					mark[v] = true;
				}
				mark[i] = true;
			}
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		fill(mark.begin(), mark.end(), false);
		for (auto a: ans)
			mark[a] = true;
		cout << n - ans.size() << '\n';
		// int j = 0;
		for (int i = 0; i < n; i++){
			if (!(mark[i]))
				cout << i + 1 << ' ';
		}
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
// vector <bool> mark;
vector <pair <int, int>> deg;
set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		deg.clear();
		adj.resize(n);
		deg.resize(n);
		// mark.clear();
		// mark.resize(n);
		D.clear();
		for (int i = 0; i < n; i++)
			deg[i].second = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			deg[v].first ++;
			adj[u].push_back(v);
			deg[u].first ++;
		}
		for (int i = 0; i < n; i++)
			D.insert(deg[i]);
		int G = 0;
		ans.clear();
		while (G != n && D.size()){
			pair <int, int> T = *(D.rbegin());
			G += 1 + T.first;
			ans.push_back(T.second);
			D.erase(deg[T.second]);
			// mark[T.second] = true;
			for (auto v: adj[T.second]){
				for (auto u: adj[v]){
					if (D.find(deg[u]) != D.end()){
						D.erase(deg[u]);
						deg[u].first --;
						D.insert(deg[u]);
					}
				}
				// mark[v] = true;
				D.erase(deg[v]);
			}
			// remove(T.second);
		}
		cout << ans.size() << '\n';
		for (auto d: ans)
			cout << d + 1 << ' ';
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
// vector <bool> mark;
vector <pair <int, int>> deg;
set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		deg.clear();
		adj.resize(n);
		deg.resize(n);
		// mark.clear();
		// mark.resize(n);
		D.clear();
		for (int i = 0; i < n; i++)
			deg[i].second = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			deg[v].first ++;
			adj[u].push_back(v);
			deg[u].first ++;
		}
		for (int i = 0; i < n; i++)
			D.insert(deg[i]);
		int G = 0;
		ans.clear();
		while (G != n && D.size()){
			pair <int, int> T = *(D.rbegin());
			G += 1 + T.first;
			ans.push_back(T.second);
			D.erase(deg[T.second]);
			// mark[T.second] = true;
			for (auto v: adj[T.second]){
				for (auto u: adj[v]){
					if (D.find(deg[u]) != D.end()){
						D.erase(deg[u]);
						deg[u].first --;
						D.insert(deg[u]);
					}
				}
				// mark[v] = true;
				D.erase(deg[v]);
			}
			// remove(T.second);
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		cout << n - ans.size();
		int j = 0;
		for (int i = 0; i < n; i++){
			if (ans[j] != i){
				cout << i + 1 << ' ';
			}
			else
				j ++;
		}
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
vector <bool> mark;
// vector <int> deg;
// set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		// deg.clear();
		adj.resize(n);
		// deg.resize(n);
		mark.clear();
		mark.resize(n);
		// D.clear();
		// for (int i = 0; i < n; i++)
			// deg[i].se/cond = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			// deg[v] ++;
			adj[u].push_back(v);
			// deg[u] ++;
		}
		// for (int i = 0; i < n; i++)
			// D.insert(deg[i]);
		int G = 0;
		ans.clear();
		for (int i = 0; i < n; i++){
			if (!(mark[i])){
				ans.push_back(i);
				for (auto v: adj[i]){
					mark[v] = true;
				}
				mark[i] = true;
			}
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		cout << n - ans.size() << '\n';
		int j = 0;
		for (int i = 0; i < n; i++){
			if (ans[j] != i){
				cout << i + 1 << ' ';
			}
			else
				j ++;
		}
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
// vector <bool> mark;
vector <pair <int, int>> deg;
set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		deg.clear();
		adj.resize(n);
		deg.resize(n);
		// mark.clear();
		// mark.resize(n);
		D.clear();
		for (int i = 0; i < n; i++)
			deg[i].second = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			deg[v].first ++;
			adj[u].push_back(v);
			deg[u].first ++;
		}
		for (int i = 0; i < n; i++)
			D.insert(deg[i]);
		int G = 0;
		ans.clear();
		while (G != n){
			pair <int, int> T = *(D.rbegin());
			G += 1 + T.first;
			ans.push_back(T.second);
			D.erase(deg[T.second]);
			// mark[T.second] = true;
			for (auto v: adj[T.second]){
				for (auto u: adj[v]){
					if (D.find(deg[u]) != D.end()){
						D.erase(deg[u]);
						deg[u].first --;
						D.insert(deg[u]);
					}
				}
				// mark[v] = true;
				D.erase(deg[v]);
			}
			// remove(T.second);
		}
		cout << ans.size() << '\n';
		for (auto d: ans)
			cout << d + 1 << ' ';
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
// vector <bool> mark;
vector <pair <int, int>> deg;
set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		deg.clear();
		adj.resize(n);
		deg.resize(n);
		// mark.clear();
		// mark.resize(n);
		D.clear();
		for (int i = 0; i < n; i++)
			deg[i].second = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			deg[v].first ++;
			adj[u].push_back(v);
			deg[u].first ++;
		}
		for (int i = 0; i < n; i++)
			D.insert(deg[i]);
		int G = 0;
		ans.clear();
		while (G != n && D.size()){
			pair <int, int> T = *(D.rbegin());
			G += 1 + T.first;
			ans.push_back(T.second);
			D.erase(deg[T.second]);
			// mark[T.second] = true;
			for (auto v: adj[T.second]){
				for (auto u: adj[v]){
					if (D.find(deg[u]) != D.end()){
						D.erase(deg[u]);
						deg[u].first --;
						D.insert(deg[u]);
					}
				}
				// mark[v] = true;
				D.erase(deg[v]);
			}
			// remove(T.second);
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		cout << n - ans.size() << '\n';
		int j = 0;
		for (int i = 0; i < n; i++){
			if (ans[j] != i){
				cout << i + 1 << ' ';
			}
			else
				j ++;
		}
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
vector <bool> mark;
// vector <int> deg;
// set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		// deg.clear();
		adj.resize(n);
		// deg.resize(n);
		mark.clear();
		mark.resize(n);
		// D.clear();
		// for (int i = 0; i < n; i++)
			// deg[i].se/cond = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			// deg[v] ++;
			adj[u].push_back(v);
			// deg[u] ++;
		}
		// for (int i = 0; i < n; i++)
			// D.insert(deg[i]);
		int G = 0;
		ans.clear();
		for (int i = 0; i < n; i++){
			if (!(mark[i])){
				ans.push_back(i);
				for (auto v: adj[i]){
					mark[v] = true;
				}
				mark[i] = true;
			}
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		cout << n - ans.size() << '\n';
		int j = 0;
		for (int i = 0; i < n; i++){
			if (ans[j] > i){
				cout << i + 1 << ' ';
			}
			else
				j ++;
		}
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
vector <bool> mark;
// vector <int> deg;
// set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		// deg.clear();
		adj.resize(n);
		// deg.resize(n);
		mark.clear();
		mark.resize(n);
		// D.clear();
		// for (int i = 0; i < n; i++)
			// deg[i].se/cond = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			// deg[v] ++;
			adj[u].push_back(v);
			// deg[u] ++;
		}
		// for (int i = 0; i < n; i++)
			// D.insert(deg[i]);
		int G = 0;
		ans.clear();
		for (int i = 0; i < n; i++){
			if (!(mark[i])){
				ans.push_back(i);
				for (auto v: adj[i]){
					mark[v] = true;
				}
				mark[i] = true;
			}
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		cout << n - ans.size() << '\n';
		int j = 0;
		for (int i = 0; i < n; i++){
			if (ans[j] < i){
				cout << i + 1 << ' ';
			}
			else
				j ++;
		}
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
vector <bool> mark;
// vector <int> deg;
// set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		// deg.clear();
		adj.resize(n);
		// deg.resize(n);
		mark.clear();
		mark.resize(n, false);
		// D.clear();
		// for (int i = 0; i < n; i++)
			// deg[i].se/cond = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			// deg[v] ++;
			adj[u].push_back(v);
			// deg[u] ++;
		}
		// for (int i = 0; i < n; i++)
			// D.insert(deg[i]);
		int G = 0;
		ans.clear();
		for (int i = 0; i < n; i++){
			if (!(mark[i])){
				ans.push_back(i);
				for (auto v: adj[i]){
					mark[v] = true;
				}
				mark[i] = true;
			}
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		cout << n - ans.size() << '\n';
		int j = 0;
		for (int i = 0; i < n; i++){
			if (ans[j] > i){
				cout << i + 1 << ' ';
			}
			else
				j ++;
		}
		cout << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
// __builtin_popcount

vector <vector <int>> adj;
// vector <bool> mark;
vector <int> deg;
// set <pair <int, int>> D;
vector <int> ans;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t --){
		int n, m;
		cin >> n >> m;
		adj.clear();
		deg.clear();
		adj.resize(n);
		deg.resize(n);
		// mark.clear();
		// mark.resize(n);
		// D.clear();
		// for (int i = 0; i < n; i++)
			// deg[i].se/cond = i;
		for (int i = 0; i < m; i++){
			int v, u;
			cin >> v >> u;
			v --;
			u --;
			adj[v].push_back(u);
			deg[v] ++;
			adj[u].push_back(v);
			deg[u] ++;
		}
		// for (int i = 0; i < n; i++)
			// D.insert(deg[i]);
		int G = 0;
		ans.clear();
		for (int i = 0; i < n; i++){
			if (deg[i] == 0)
				continue;
			G += 1 + deg[i];
			for (auto v: adj[i]){
				for (auto u: adj[v]){
					if (deg[v])
						deg[u] --;
					deg[u] = max(deg[u], 0);
				}
				deg[v] = 0;
			}
			deg[i] = 0;
			ans.push_back(i);
		}
		if (ans.size() <= n / 2){
			cout << ans.size() << '\n';
			for (auto d: ans)
				cout << d + 1 << ' ';
			cout << '\n';
			continue;
		}
		cout << n - ans.size() << '\n';
		int j = 0;
		for (int i = 0; i < n; i++){
			if (ans[j] != i){
				cout << i + 1 << ' ';
			}
			else
				j ++;
		}
		cout << '\n';
	}
}


#include<bits/stdc++.h>
using namespace std;
#define fi              first
#define se              second
#define ll              long long
#define int             long long int
#define pb              push_back
#define mp              make_pair
#define pll             pair<ll,ll>
#define vll             vector<ll>
#define mll             map<ll,ll>
#define setbits(x)      __builtin_popcountll(x)
#define md              1e9 +7
#define inf             1e18
#define ps(x,y)         fixed<<setprecision(y)<<x
#define f(i,j,n)        for(ll i=j;i<n;i++)
#define r(i,j,n)        for(ll i=n-1;i>=j;i--)
vll v[1000000];
ll l[1000000]={0}; // level
bool vis[1000000];//make it false
void dfs(ll s)
{
    vis[s] = true;
    for(auto u : v[s])
    {
        if(!vis[u])
        {
           l[u]=l[s]+1;
           dfs(u);
        }
    }
}
void solve()
{
    ll n,m;cin>>n>>m; memset(vis,false,sizeof(vis)); //vll v[n+5];
    for(int i=0;i<m;i++)
    {
        ll x,y; cin>>x>>y;
        v[x].pb(y);
        v[y].pb(x);
    }
    dfs(1);
    vll ans,ans1;
    for(int i=1;i<=n;i++)
    if(l[i]%2==1)   ans.pb(i);
    else ans1.pb(i);
    if(ans1.size()<=ans.size())   for(auto i : ans1)  cout<<i<<" ";
    else  for(auto i : ans) cout<<i<<" ";
    cout<<"\n";
    for(int i=0;i<n+10;i++) v[i].clear(),l[i]=0;
}
int32_t main()
{
    ios_base::sync_with_stdio(false);   cin.tie(NULL);
    #ifndef ONLINE_JUDGE
    freopen("inpput.txt", "r", stdin); //freopen("op.txt", "w", stdout);
    #endif
    ll test_cases=1; cin>>test_cases;
    for(ll t=1;t<=test_cases;t++)
        solve();
    //cerr<<"Time : "<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<"ms\n";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define fi              first
#define se              second
#define ll              long long
#define int             long long int
#define pb              push_back
#define mp              make_pair
#define pll             pair<ll,ll>
#define vll             vector<ll>
#define mll             map<ll,ll>
#define setbits(x)      __builtin_popcountll(x)
#define md              1e9 +7
#define inf             1e18
#define ps(x,y)         fixed<<setprecision(y)<<x
#define f(i,j,n)        for(ll i=j;i<n;i++)
#define r(i,j,n)        for(ll i=n-1;i>=j;i--)
vll v[1000000];
ll l[1000000]={0}; // level
bool vis[1000000];//make it false
void bfs(ll root) {
    queue <ll> q;
    q.push(root);
    l[ root ] = 0 ;
    vis[ root ] = true;
    while(!q.empty())
    {
        ll s = q.front();
        q.pop();
        for(auto u : v[ s ])
        {
            if(!vis[ u ])
            {
                l[ u ] = l[ s ]+1;
                q.push(u);
                vis[ u] = true;
            }
        }
    }
}
void solve()
{
    ll n,m;cin>>n>>m; memset(vis,false,sizeof(vis)); //vll v[n+5];
    for(int i=0;i<n+10;i++) v[i].clear(),l[i]=0;
    for(int i=0;i<m;i++)
    {
        ll x,y; cin>>x>>y;
        v[x].pb(y);
        v[y].pb(x);
    }
    bfs(1);
    vll ans;
    for(int i=1;i<=n;i++)   if(l[i]%2==1)   ans.pb(i);
    sort(ans.begin(),ans.end());
    cout<<min((ll)ans.size(),n/2)<<"\n";
    if(ans.size()<=n/2)
    for(int i=1;i<=n;i++)  {if(binary_search(ans.begin(),ans.end(),i)) cout<<i<<" ";}
    else
    for(int i=1;i<=n;i++)  {if(!binary_search(ans.begin(),ans.end(),i)) cout<<i<<" ";}
    cout<<"\n";
}
int32_t main()
{
    ios_base::sync_with_stdio(false);   cin.tie(NULL);
    #ifndef ONLINE_JUDGE
    freopen("inpput.txt", "r", stdin); //freopen("op.txt", "w", stdout);
    #endif
    ll test_cases=1; cin>>test_cases;
    for(ll t=1;t<=test_cases;t++)
        solve();
    //cerr<<"Time : "<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<"ms\n";
    return 0;
}