a, b, c, d, m = map(int, input().split())
res = 0
for x in range(a, b+1):
    for y in range(c, d+1):
        res = max(res, (x+y)%m)
print(res)