#include <bits/stdc++.h>
//#include<atcoder/all>
using namespace std;
//using namespace atcoder;
using ll = long long;
#define all(A) A.begin(),A.end()
using vll = vector<ll>;
#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)
using Graph = vector<vector<ll>>;


int main() {
    ll A, B, C, D, M;
    cin >> A >> B >> C >> D >> M;
    ll an = 0;
    for (ll X = A; X <= B; X++)for (ll Y = C; Y <= D; Y++) {
        an = max(an, (X + Y) % M);
    }
    cout << an << endl;
}