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): v[0][i] = pow(i+d, i, b) for i in range(59): for j in range(b): v[i+1][j] = v[i][v[i][j]] m %= b for i in range(60): if (n >> i) & 1: m = v[i][m] r = '0123456789ABCDEFG' print(r[m])