import sys
t = int(sys.stdin.readline())
while(t != 0):
a,d,r = sys.stdin.readline().split()
n,mod = sys.stdin.readline().split()
a = int(a)
mod = int(mod)
d = int(d)
r = int(r)
n = int(n)
if( r == 1):
sys.stdout.write(str((a+(n/2)*d)%mod)+'\n')
elif(r != 1):
p = (n-1)/2
r1 = r-1
res = (((r**p)*(d*r + a*r1))/r1)-((d*r)/r1)
if(n % 2 == 1 and r != 1):
sys.stdout.write(str(res%mod)+'\n')
else:
sys.stdout.write(str((res+d)%mod)+'\n')
t = t-1
i hanged the codes twice but still tle... why time so strict.. help me out plzzzz