import random from math import gcd def pfact(m): pf = {} for i in range(2,int(m**0.5)+1): while m%i == 0: pf[i] = pf.get(i,0) + 1 m //= i if m>1 : pf[m]=1 return pf def euler(m): #pfactのdefが必須 tmp = pfact(m) ans = 1 for i, j in tmp.items(): ans = ans * (i**(j-1)) * (i-1) return ans while True: """ m = random.randrange(0, 10) d = random.randrange(0, 10) n = random.randrange(0, 1000) b = random.randrange(2, 12) """ m = int(input()) d = int(input()) n = int(input()) b = int(input()) """ m = 9 d = 3 n = 82 b = 9 """ def fast(m,d,n,b): nb = b * euler(b) // gcd(b, euler(b)) v = [[0] * nb for i in range(61)] for i in range(nb): if (i+d)%nb != 0: v[0][i] = pow(i+d, i, nb) else: v[0][i] = 0 for i in range(60): for j in range(nb): v[i+1][j] = v[i][v[i][j]] if n == 0: r = '0123456789ABCDEFG' return r[m % nb] if m == 0 and d == 0: n -= 1 m = 1 m %= nb for i in range(61): if (n >> i) & 1: m = v[i][m] r = '0123456789ABCDEFG' return r[m % b] def naive(m,d,n,b): if n == 0: r = '0123456789ABCDEFG' return r[m % b] if m == 0: n -= 1 if d == 0: m = 1 else: if (m+d)%b == 0: m = 0 else: m = pow(m+d, m, b) m %= b for i in range(n): if (m+d)%b != 0: m = pow(m+d, m, b) else: m = 0 r = '0123456789ABCDEFG' return r[m] #if fast(m,d,n,b) != naive(m,d,n,b): # print(m,d,n,b) # print(fast(m,d,n,b), naive(m,d,n,b)) # break print(fast(m,d,n,b)) break