a, b, c, d, m = map(int,input().split()) if (b + d) - (a + c) + 1 >= m: print(m - 1) elif (b + d)%m < (a + c)%m: print(m - 1) else: print((b + d)%m)