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