a,b,c,d,m=map(int, input().split()) lst=[] for x in range(a+c,b+d+1): lst.append(x % m) print(max(lst))