import sys input = sys.stdin.readline def read_values(): return tuple(map(int, input().split())) def floor_sum(n,m,a,b): res=0 if a>=m: res+=n*(n-1)//2*(a//m) a%=m if b>=m: res+=n*(b//m) b%=m last=a*(n-1)+b if last>=m: lastdiv=last//m lastmod=last%m res+=lastdiv+floor_sum(lastdiv,a,m,lastmod) return res def main(): q=int(input()) for _ in range(q): n,d,m,s=read_values() l=0 r=n+1 ts=2.0**s while l+1 n * m: ans=d-1 else: ts=2**s ans-=abs(floor_sum(right,d,1,1)-floor_sum(right,ts,m,m)) print(ans) if __name__ == "__main__": main()