import time
import math

# L1 < L2 < L3 ...
# K < L1 ... leaf
# L1 <= K < L2  only left child
# L2 <= K < L3  only right child
# L3 <= K both children
# depth <= D, depth(root) == 0;
# A, B, C, M:
# left child key value (AK + B) % M
# right child key value (AK + 2B) % M
# R root key value

A = 0; B = 0;  D = 0; L1 = 0; L2 = 0; L3 = 0; M = 0; R = 0; calls = 0

def sumLeaves (K, depth):
    global calls
    calls = calls + 1

    if K < L1 or depth == D:
        #print("[" + str(K)+ "] d:", str(depth), " --- ")
        return K

    if K < L2:
       # print("[" + str(K)+ "] d:", str(depth), " L", (A*K + B) % M)
        return sumLeaves ( (A*K + B) % M, depth+1 )

    if K < L3:
        #print("[" + str(K)+ "] d:", str(depth), " R", (A*K + 2*B) % M)
        return sumLeaves ( (A*K + 2*B) % M, depth+1 )

    #print("[" + str(K)+ "] d:", str(depth), " L", (A*K + B) % M, " R", (A*K + 2*B) % M)
    return sumLeaves ( (A*K + B) % M, depth+1 ) \
           + sumLeaves ( (A*K + 2*B) % M, depth+1 )

# ----------------------------------------------------------------------------
#                M A I N   P R O G R A M
# ----------------------------------------------------------------------------


#A, B, M,  L1, L2, L3, D, R = map(int, test0x.split())
A, B, M, L1, L2, L3, D, R = map(int, input().split())
calls = 0

time1 = time.time()
sum = sumLeaves(R, 0)
time2 = time.time()
print(sum)
#print("calls and nodes", calls)
#   print("time %5d ms" % int(math.floor((time2 - time1) * 1000)) )







