#define _USE_MATH_DEFINES

#include <iostream>		//cin, cout
#include <vector>		//vector
#include <algorithm>	//sort,min,max,count
#include <string>		//string,getline, to_string
#include <cstdlib>		//abs(int)
#include <utility>		//swap, pair
#include <deque>		//deque
#include <climits>		//INT_MAX
#include <bitset>		//bitset
#include <cmath>		//sqrt, ceil. M_PI, pow, sin
#include <ios>			//fixed
#include <iomanip>		//setprecision
#include <sstream>		//stringstream
#include <numeric>		//gcd, assumlate
#include <random>		//randam_device
#include <limits>		//numeric_limits

using namespace std;
constexpr long long int D_MOD = 1000000007;

int main() {

	int a, b, c, d, m;
	cin >> a >> b >> c >> d >> m;

	int max = 0;
	int temp;

	if (a == b) {
		for (int i = c; i <= d; i++) {
			temp = (b + i) % m;
			if (temp > max) {
				max = temp;
			}
		}
	}
	else if (c == d) {
		for (int i = a; i <= b; i++) {
			temp = (d + i) % m;
			if (temp > max) {
				max = temp;
			}
		}
	}
	else if (a == b && c == d) {
		max = (b + d) % m;
	}
	else {
		for (int i = a; i <= b; i++) {
			for (int j = c; j <= d; j++) {
				temp = (i + j) % m;
				if (temp > max) {
					max = temp;
				}
			}
		}
	}

	cout << max << endl;

	return 0;

}