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