M = int(input()) D = int(input()) N = int(input()) B = int(input()) if N == 0: res = M % B else: current_mod = M % B history = [current_mod] pos_map = {current_mod: 0} found_cycle = False cycle_start = 0 cycle_length = 0 for step in range(1, N + 1): a = (current_mod + D) % B e = current_mod if a == 0 and e == 0: next_mod = 1 % B elif a == 0: next_mod = 0 % B else: next_mod = pow(a, e, B) if next_mod in pos_map: cycle_start = pos_map[next_mod] cycle_length = len(history) - cycle_start remaining = N - step final_pos = cycle_start + (remaining % cycle_length) current_mod = history[final_pos] found_cycle = True break else: pos_map[next_mod] = len(history) history.append(next_mod) current_mod = next_mod res = current_mod # Convert res to B base last digit if res < 10: print(res) else: print('A')