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