M = int(input()) D = int(input()) N = int(input()) B = int(input()) D_mod = D % B current = M % B if N == 0: res = current else: history = [current] seen = {current: 0} found_cycle = False ans = current for step in range(1, N + 1): a = (current + D_mod) % B e = current if a == 0 and e == 0: next_x = 1 % B else: next_x = pow(a, e, B) if next_x in seen: cycle_start = seen[next_x] cycle_length = step - cycle_start remaining = N - step pos = cycle_start + (remaining % cycle_length) ans = history[pos] found_cycle = True break seen[next_x] = step history.append(next_x) current = next_x if step == N: ans = current found_cycle = True break if not found_cycle: ans = current if ans < 10: print(ans) else: print('A')