def f(n,m,a);b=r=0;while n>0;r+=a/m*n*~-n/2+b/m*n;a%=m;b%=m;y=a*n+b;n,b,m,a=y/m,y%m,a,m;end;r;end;gets.to_i.times{n,d,m,s=gets.split.map &:to_i;p,q=1<