import sys readline=sys.stdin.readline T=int(readline()) for t in range(T): N,M,X,Y=map(int,readline().split()) A=[(i*X+Y)%M for i in range(N)] B=[(i*X+Y)//M for i in range(N)] ans=sum(B[i]*(2*i-(N-1)) for i in range(N)) for d in range(1,N): ans-=d*X//M*(N-d) print(ans)