def main(): a, c, b, d, m = map(int, input().split()) if (c+d)//m > (a+b)//m: print(m-1) else: print((c+d) % m) if __name__ == '__main__': main()