#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll MOD=1000000000+7; #define rep(I,N) for(int I=0;I<N;I++) #define ALL(x) x.begin(),x.end() #define PRINTV(x) for(auto i:x){for(auto j:i){printf("%d\t",j);}printf("\n");} using vec = vector<int>; using vvec = vector<vector<int>>; ll lcm(ll a,ll b){ return a/__gcd(a,b)*b; } //template<typename T> vector<ll> findall(string target,string find_word){ vector<ll> a; ll pos=target.find(find_word); while(pos!=std::string::npos){ a.push_back(pos); pos=target.find(find_word,pos+find_word.length()); } return a; } int main(){ int a,b,c,d,m; cin >> a >> b >> c >> d >> m; int MAX=-1; for(int i=a;i<=b;i++){ for(int j=c;j<=d;j++){ MAX=max(MAX,(i+j)%m); } } printf("%d",MAX); }