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