def scary_sum_naive(p,q,N,M,A,B): return sum(pow(i,p,998244353)*pow((A*i+B)//M,q,998244353) for i in range(N)) T=int(input()) for _ in range(T): temp=list(map(int,input().split())) if temp[2]>1e6: assert 0 temp[2]+=1 print(scary_sum_naive(*temp)%998244353)