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