def f(n,m,a): b=r=0 while n>0:r+=a//m*n*~-n//2+b//m*n;a%=m;b=a*n+b%m;n=b//m;b%=m;m,a=a,m return r for _ in[0]*int(input()): n,d,m,s=map(int,input().split());p,q=1<