a,b,c,d,m=map(int,input().split());print(max((x+y)%m for x in range(a,b+1)for y in range(c,d+1)))