import sys input=lambda:sys.stdin.readline().rstrip() a,b,c,d,m=map(int,input().split()) print(max([i%m for i in range(a+c,b+d+1)]))