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