from collections import defaultdict *V, n = map(int, input().split()) now = [0] * 4 now[0] = V[0] idx = defaultdict(lambda : -1) route = [now[:]] for i in range(1000000): l, r = i % 4, (i + 1) % 4 move = min(now[l], V[r] - now[r]) now[l] -= move now[r] += move tpn = tuple(now) if tpn in idx: break idx[tpn] = i route.append(now[:]) loop = idx[tuple(now)] + 1 if n < loop: print(route[n]) else: route = route[loop:] n -= loop print(route[n % len(route)])