A, B, C, D, M = map(int, input().split()) if (A + C) // M < (B + D) // M: print(M - 1) else: print((B + D) % M)