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;end;r;end;gets.to_i.times{n,d,m,s=gets.split.map &:to_i;p,q=1<