m = int(input()) d = int(input()) n = int(input()) b = int(input()) v = [[0] * b for i in range(60)] for i in range(b): if (i+d)%b != 0: v[0][i] = pow(i+d, i, b) else: v[0][i] = 0 for i in range(59): for j in range(b): v[i+1][j] = v[i][v[i][j]] m %= b if n == 0 and m == 0 and d == 0: print(0) exit() if m == 0 and d == 0: n -= 1 m = 1 for i in range(60): if (n >> i) & 1: m = v[i][m] r = '0123456789ABCDEFG' print(r[m])