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