#include <bits/stdc++.h>

using namespace std;
void fast_io() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
}

int main() {
    fast_io();
    int a, b, c, d, m;
    cin >> a >> b >> c >> d >> m;
    int ans = 0;
    for (int x = a; x <= b; x++) {
        for (int y = c; y <= d; y++) {
            ans = max(ans, (x + y) % m);
        }
    }
    cout << ans << endl;
}