At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly $$$k$$$ candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends in the circle. Lena knows, that some of her friends have a sweet tooth and others do not. Sweet tooth takes out of the box two candies, if the box has at least two candies, and otherwise takes one. The rest of Lena's friends always take exactly one candy from the box.Before starting to give candies, Lena step out of the circle, after that there were exactly $$$n$$$ people remaining there. Lena numbered her friends in a clockwise order with positive integers starting with $$$1$$$ in such a way that index $$$1$$$ was assigned to her best friend Roma.Initially, Lena gave the box to the friend with number $$$l$$$, after that each friend (starting from friend number $$$l$$$) took candies from the box and passed the box to the next friend in clockwise order. The process ended with the friend number $$$r$$$ taking the last candy (or two, who knows) and the empty box. Please note that it is possible that some of Lena's friends took candy from the box several times, that is, the box could have gone several full circles before becoming empty.Lena does not know which of her friends have a sweet tooth, but she is interested in the maximum possible number of friends that can have a sweet tooth. If the situation could not happen, and Lena have been proved wrong in her observations, please tell her about this.

The only line contains four integers $$$n$$$, $$$l$$$, $$$r$$$ and $$$k$$$ ($$$1 \le n, k \le 10^{11}$$$, $$$1 \le l, r \le n$$$) — the number of children in the circle, the number of friend, who was given a box with candies, the number of friend, who has taken last candy and the initial number of candies in the box respectively.

Print exactly one integer — the maximum possible number of sweet tooth among the friends of Lena or "-1" (quotes for clarity), if Lena is wrong.

NoteIn the first example, any two friends can be sweet tooths, this way each person will receive the box with candies twice and the last person to take sweets will be the fourth friend.In the second example, sweet tooths can be any three friends, except for the friend on the third position.In the third example, only one friend will take candy, but he can still be a sweet tooth, but just not being able to take two candies. All other friends in the circle can be sweet tooths as well, they just will not be able to take a candy even once.In the fourth example, Lena is wrong and this situation couldn't happen.

#include <iostream>
#include <fstream>
using namespace std;

long long bs(long long t,long long l,long long r,long long h,long long x,long long n)
{
    long long mid,tp=-1;
    while (l<=r)
    {
        mid=(l+r)/2;
        if (mid<(t-mid*x) || (t-mid*x)>h) l=mid+1; else
        if (mid-(t-mid*x)<=n-h && (t-mid*x)<=h)
        {
            l=mid+1;
            tp=mid;
        } else r=mid-1;
    }
    return tp;
}

int main()
{
    //freopen("m.inp","r",stdin);
    //freopen("m.out","w",stdout);
    long long n,l,r,k,h,t,m2=-1;
    cin>>n>>l>>r>>k;
    if (r>=l) h=r-l+1; else h=n-l+1+r;
    if (k<h)
    {
        cout<<-1;
        return 0;
    }
    if (n<=1000000)
    {
        for (int m=n;m>=0;m--)
        {
            t=k%(n+m);
            if ((t>=max(h,m-n+2*h) && t<=min(m+h,2*h)) || (t==0 && ((l==1 && r==n) || (l-1==r))))
            {
                m2=m;
                break;
            }
        }
        k=k+1;
        for (int m=n;m>=1;m--)
        {
            t=k%(n+m);
            if ((t>=max(h+1,m-n+2*h) && t<=min(m+h,2*h)) || (t==0 && ((l==1 && r==n) || (l-1==r))))
            {
                if (m>m2) m2=m;
                break;
            }
        }
        cout<<m2;
    }
    else
    {
        long long m3;
        if (k<=2*h) m2=k-h+(n-h);
        for (int i=1;i<=k/n;i++)
        {
            t=k-n*i-h;
            m3=bs(t,0,n,h,i,n);
            if (m3!=-1)
            {
                if (m3>m2) m2=m3;
                break;
            }
        }
        k=k+1;
        if (k<=2*h) m2=k-h+(n-h);
        for (int i=1;i<=k/n;i++)
        {
            t=k-n*i-h;
            m3=bs(t,0,n,h,i,n);
            if (m3!=-1)
            {
                if (m3>m2) m2=m3;
                break;
            }
        }
        cout<<m2;
    }
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll n, x, k, lb, ub, ans = -1;

void init() {
    ll l, r;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    x = (r >= l ? r - l + 1 : r + n - l + 1) % n;
}

void solve() {
    for(ll i = k, j, r; i; i = j) {
        j = k / (k / i + 1); r = k / i;
        ub = min(2 * n, i);
        lb = max(n, j + 1);
        ub = min(ub, min((2 * n + k - 2 * x + 1) / (r + 1), (k - x) / r));
        lb = max(lb, (k - 2 * x + r - 1) / r);
        if(ub >= lb) ans = max(ans, ub);
    }
    if(x <= k && k <= x * 2) ans = max(ans, n + min(k - x, x - 1) + n - x + 1);
    if(!x && k == n) ans = max(ans, n + 1);
    printf("%lld\n", ~ans ? ans - n : ans);
}

int main() {
    init();
    solve();
}

#include <bits/stdc++.h>

using namespace std;
typedef long long INT;
typedef double DO;
typedef pair<int, int> pii;
typedef vector<int> VI;

#define x first
#define y second
#define pb push_back

int power(int a, int b, int c, int ans=1) {
	for (; b; b>>=1, a=(INT)a*a%c) if (b&1) ans=(INT)ans*a%c;
	return ans;
}

INT calc(INT n, INT l, INT r, INT k, int ok=0) {
	INT c = l<=r ? r-l+1 : n+r-l+1;
	if (k<c) return -1;
	k-=c;
	INT ans = -1;
	if (n<1e6) {
		for (INT y=n; y>=0; y--) {
			INT x = k % (n + y);
			if (x>=ok && x<=c && x<=y && y-x<=n-c) return y;
		}
	} else {
		for (INT s=0, t=k; t>=0; t-=n, s++) {
			if (s==0) {
				if (t>=ok && t<=c) return t+n-c;
			} else {
				INT x = t % s, y = t / s;
				if (y < x || x > c) continue;
				if (y < ans) break;
				INT ed = min((y-x)/(s+1), (c-x)/s);
				INT st = max(ok>x?1LL:0LL, (y-x-n+c+s)/(s+1));
				if (st<=ed) ans = max(ans, y-st);
			}
		}
	}
	return ans;
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("in.in", "r", stdin);
	freopen("out.out", "w", stdout);
#endif

	INT n, l, r, k;
	cin>>n>>l>>r>>k;

	cout << max(calc(n, l, r, k), calc(n, l, r, k+1, 1)) << endl;

	return 0;
}

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

long long N, K, L, R, S, maxn = -1;

int main() {
	cin >> N >> L >> R >> K;
	S = (R - L + 1 + N) % N;

	// 1 周以上の場合
	long long B = K / (2LL * N); if (B == 0) B = 1;
	vector<long long>E;
	for (long long i = 2LL * N; i >= 2LL * N - 2000; i--) {
		if (i < N) break;
		for (long long j = 0; j <= 3; j++) E.push_back(K / i + j);
		for (long long j = 0; j <= 3; j++) E.push_back((K + 1) / i + j);
	}
	sort(E.begin(), E.end());
	E.erase(unique(E.begin(), E.end()), E.end());

	for (long long i : E) {
		if (i == 0) continue;
		long long BASE = (1LL * i + 1LL) * S + (1LL * i) * (N - S);
		if (K < BASE) continue;

		long long UPLIMIT_1 = N - S;
		long long UPLIMIT_2 = S;
		long long SA1 = K - BASE;
		long long V1 = SA1 / i;
		long long V2 = SA1 % i; V1 -= V2;
		long long SABUN = V1 - UPLIMIT_1;
		if (SABUN > 0) { long long P = (SABUN + i) / (i + 1); V1 -= 1LL * (i + 1)*P; V2 += 1LL * i*P; }

		if (V1 < 0 || V2 < 0 || V1 > UPLIMIT_1 || V2 > UPLIMIT_2) continue;

		long long sum = V1 + V2;
		maxn = max(maxn, sum);
	}

	// 1 周以上で合計が K + 1 以上の場合
	for (long long i : E) {
		if (i == 0) continue;
		long long BASE = (1LL * i + 1LL) * S + (1LL * i) * (N - S);
		if (K + 1 < BASE) continue;

		long long UPLIMIT_1 = N - S;
		long long UPLIMIT_2 = S;
		long long SA1 = K + 1 - BASE;
		long long V1 = SA1 / i;
		long long V2 = SA1 % i; V1 -= V2;
		long long SABUN = V1 - UPLIMIT_1;
		if (SABUN > 0) { long long P = (SABUN + i) / (i + 1); V1 -= 1LL * (i + 1)*P; V2 += 1LL * i*P; }
		if (V2 == 0 && S != 0) { V2 += i; V1 -= (i + 1); }

		if (V1 < 0 || V2 < 0 || V1 > UPLIMIT_1 || V2 > UPLIMIT_2) continue;

		long long sum = V1 + V2;
		maxn = max(maxn, sum);
	}

	// 0 周の場合
	if (true) {
		if (K == S) maxn = max(maxn, 1LL + (N - S));
		else if (K > S && K <= 2LL * S) maxn = max(maxn, min(S, K - S + 1) + (N - S));
	}
	cout << maxn << endl;
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define FOR(i, j, k) for(ll i=(j); i<=(k); i++)
#define FFOR(i, j, k) for(ll i=(j); i<(k); i++)
#define DFOR(i, j, k) for(ll i=(j); i>=(k); i--)
#define bug(x) cerr<<#x<<" = "<<(x)<<'\n'
#define pb push_back
#define mp make_pair
#define setbit(s, i) (s|=(1LL<<(i)))
#define bit(s, i) (((s)>>(i))&1LL)
#define mask(i) ((1LL<<(i)))
#define builtin_popcount __builtin_popcountll
using ll=long long;
using ld=long double;
template <typename T> inline void read(T &x){
    char c;
    bool nega=0;
    while((!isdigit(c=getchar()))&&(c!='-'));
    if(c=='-'){
        nega=1;
        c=getchar();
    }
    x=c-48;
    while(isdigit(c=getchar())) x=x*10+c-48;
    if(nega) x=-x;
}
template <typename T> inline void writep(T x){
    if(x>9) writep(x/10);
    putchar(x%10+48);
}
template <typename T> inline void write(T x){
    if(x<0){
        putchar('-');
        x=-x;
    }
    writep(x);
}
template <typename T> inline void writeln(T x){
    write(x);
    putchar('\n');
}
#define taskname "D"
ll n, k, l, r;
int main(){
    #ifdef Uiharu
        if(fopen(taskname".in", "r"))
            freopen(taskname".in", "r", stdin);
    #endif // Uiharu
    read(n);
    read(l);
    read(r);
    read(k);
    r-=l;
    r%=n;
    r+=n+1;
    r%=n;
    if(n<=1000000){
        ll c, inmax;
        DFOR(x, n, 0){
            c=k%(n+x);
            if(c<r) continue;
            if(c>r+r) continue;
            if(c>r+x) continue;
            if(c==r*2) inmax=c-r;
            else inmax=c-r+1;
            if(x-inmax>n-r) continue;
            writeln(x);
            return 0;
        }
        writeln(-1);
    }
    else{
        if(r==0) r=n;
        ll ans=-1;
        ll low, high;
        FOR(d, 1, 100000){
            ///k=d*(n+x)+c
            ///k>=(n+x)*d
            ///k<(d+1)*(n+x)
            ///d<=k/x<d+1
            high=(k/d)+2;
            while(high*d>k) high--;
            low=(k/(d+1))-2;
            while(low*(d+1)<=k) low++;
            low=max(low, n);
            high=min(high, n+n);
            if(low>high) continue;
            ll left=low, right=high, mid, first=0, c, inmax, last=0;
            while(left<=right){
                mid=(left+right)/2;
                c=k%mid;
                if((c>(r*2))||(c>r+mid-n)){
                    left=mid+1;
                }
                else{
                    first=mid;
                    right=mid-1;
                }
            }
            left=first, right=high;
            while(left<=right){
                mid=(left+right)/2;
                c=k%mid;
                if(((mid-n-c)>n-r*2+1)){
                    right=mid-1;
                }
                else{
                    last=mid;
                    left=mid+1;
                }
            }
            if(last==0||first==0) continue;
            FOR(cnt, -5, 5){
                ll x=last-cnt;
//                if(x<first) break;
                x-=n;
                if(x<0) break;
                c=k%(n+x);
                if(c<r) continue;
                if(c>r+r) continue;
                if(c>r+x) continue;
                if(c==r*2) inmax=c-r;
                else inmax=c-r+1;
                if(x-inmax>n-r) continue;
                ans=max(ans, x);
            }
        }
        ///d=0
        if((k<=r*2)&&(k>=r)){
            ans=max(ans, k-r+(k!=r*2)+(n-r));
        }
        writeln(ans);
    }
}

#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define LL long long
#define FOR(i,a,b) for (int i=a;i<=b;++i)
#define FORD(i,a,b) for (int i=a;i>=b;--i)
using namespace std;
typedef pair<int,int> pa;
void getint(int &v){
    char ch,fu=0;
    for(ch='*'; (ch<'0'||ch>'9')&&ch!='-'; ch=getchar());
    if(ch=='-') fu=1, ch=getchar();
    for(v=0; ch>='0'&&ch<='9'; ch=getchar()) v=v*10+ch-'0';
    if(fu) v=-v;
}
LL n,k,l,r,t,lx,ly,rx,ry,ans;
int main(){
	cin>>n>>l>>r>>k;
	if (r>=l) t=r-l+1;
	else t=r+n-l+1;
	ans=-1;
	for (LL y=0;y<=2000000;++y){
		if (y>n) break;
		if (k-y+n-t*2<0) continue;
		rx=(k-y+n-t*2)/(y+n);

		if (k-t<0) continue;

		rx=min(rx,(k-t)/(y+n));

		LL tt=max(0ll,k-t-t);
		if (tt%(y+n)==0) lx=tt/(y+n);
		else lx=tt/(y+n)+1;
		if (lx<=rx) ans=max(ans,y);
	}

	if (t*2>=k && t<=k) ans=max(ans,min(n,k+n-t*2));

	for (LL x=1;x<=2000000;++x){
		LL tt=k-x*n+n-t*2;
		if (tt<0) continue;
		ry=tt/(x+1);

		if (k-t<0) continue;
		ry=min(ry,(k-t)/x-n);

		if (ry<0) continue;
		tt=max(0ll,k-t*2-x*n);
		if (tt%x==0) ly=tt/x;
		else ly=tt/x+1;
		ry=min(ry,n);
		if (ly<=ry) ans=max(ans,ry);
	}

	++k;

	for (LL y=0;y<=2000000;++y){
		if (y>n) break;
		if (k-y+n-t*2<0) continue;
		rx=(k-y+n-t*2)/(y+n);

		if (k-(t+1)<0) continue;

		rx=min(rx,(k-(t+1))/(y+n));

		LL tt=max(0ll,k-t-t);
		if (tt%(y+n)==0) lx=tt/(y+n);
		else lx=tt/(y+n)+1;
		if (lx<=rx && y>0) ans=max(ans,y);
	}

	if (t*2>=k && t<=k && min(n,k+n-t*2)>0) ans=max(ans,min(n,k+n-t*2));

	for (LL x=1;x<=2000000;++x){
		LL tt=k-x*n+n-t*2;
		if (tt<0) continue;
		ry=tt/(x+1);

		if (k-(t+1)<0) continue;
		ry=min(ry,(k-(t+1))/x-n);

		if (ry<0) continue;
		tt=max(0ll,k-t*2-x*n);
		if (tt%x==0) ly=tt/x;
		else ly=tt/x+1;
		ry=min(ry,n);
		if (ly<=ry && ry>0) ans=max(ans,ry);
	}

	cout<<ans<<endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define rep(i, a, b) for(int i=(a); i<(b); i++)
#define per(i, a, b) for(int i=(b)-1; i>=(a); i--)
#define sz(a) (int)a.size()
#define de(a) cout << #a << " = " << a << endl
#define dd(a) cout << #a << " = " << a << " "
#define all(a) a.begin(), a.end()
#define pw(x) (1ll<<(x))
#define endl "\n"
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
ll n, l, r, k;

bool checks(ll s)
{
	ll x = (k-r+l-1)/(n+s);
	ll sp = k-r+l-1 - x*(n+s);
	if(sp < r-l+1)
		sp++;
	if(sp > r-l+1)
	{
		return false;
	}
	if(s-sp > n-r+l-1)
	{
		return false;
	}
	return true;
}

int main()
{
	ios_base::sync_with_stdio(0);
	cin >> n >> l >> r >> k;
	if(l > r) r+=n;
	if(k < r-l+1)
	{
		cout << "-1";
		return 0;
	}
	if(n < 1e6)
	{
		ll res=-1;
		ll s=0, sp=0;
		for(s=0; s <= n; s++)
		{
			if(checks(s))
				res = s;
		}
		cout << res << "\n";
	}
	else
	{
		ll res = -1;
		ll m = k-r+l-1;
		for(ll x=1; x < 1e6; x++)
		{
			ll a, b;
			a = (m-x*n-r+l-1)/x;
			b = (m-x*n+n-r+l)/(x+1);
			b = min(b, n);
			if(a <= b && checks(b))
				res = max(res, b);
			else if(a+1 <= b && checks(b-1))
				res = max(res, b-1);
		}
		ll sp = k-r+l-1;
		if(sp < r-l+1)
			sp++;
		if(sp >= 0 && sp <= r-l+1)
		{
			res = max(res, n-r+l-1+sp);
		}
		cout << res << "\n";
	}
	return 0;
}

#include<bits/stdc++.h>
using namespace std;

#define F(i,a,b) for(int i=a;i<=b;i++)
#define D(i,a,b) for(int i=a;i>=b;i--)
#define ms(i,a)  memset(a,i,sizeof(a))
#define LL       long long
template<class T>void read(T &x){
	x=0; char c=getchar();
	while (c<'0' || c>'9') c=getchar();
	while (c>='0' && c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
}
template<class T>void write(T x){
	if(x<0) x=-x,putchar('-');
	if(x>9) write(x/10);
	putchar(48+x%10);
}
template<class T>void chkmax(T &x,T y){ x=x>y? x:y; }
LL n,k,l,r,x,t,s,p,ans,y;
LL const inf=1LL<<50;
LL calc(LL p,LL s,int a,int b){
	if(a==0 || b==1){
		if(k-s-x>=0 && (k-s-x)%(n+p)==0)
			return p;
		else return -1;
	}else {
		if(k-s+1-x>=0 && (k-s+1-x)%(n+p)==0)
			return p;
		else return -1;
	}
}

LL exgcd(LL &x,LL &y,LL a,LL b){
	if(!b){
		x=1;y=0; return a;
	}
	LL t=exgcd(y,x,b,a%b);
	y-=a/b*x;
	return t;
}
void solve(LL t1,LL t2,LL c,LL add){
	if(t2==0){
		if(2*x>=k && k>=x) chkmax(ans,min(x,k-x+1)+y);
		return;
	}
	LL a,b;
	LL g=exgcd(a,b,t1,t2);
	a=a*c; b=b*c;
	LL l=-inf,r=inf;
	a-=add;
	if (a>=0) r=min(r,a/t2); else  r=min(r,(a-t2+1)/t2); a+=add;
	if(a-x>=0) l=max(l,(a-x+t2-1)/t2); else l=max(l,(a-x)/t2);
	if(y-b>=0) r=min(r,(y-b)/t1); else r=min(r,(y-b-t1+1)/t1);
	if(-b>=0) l=max(l,(-b+t1-1)/t1); else l=max(l,-b/t1);
	if(l<=r){
		chkmax(ans,a+b+l);
		chkmax(ans,a+b+r);
	}
}
int main(){
	read(n);
	read(l);
	read(r);
	read(k);
	x=(r-l+n)% n+1;
	y=n-x;
	ans=-1;
	if(k/n>=5000000){
		F(p,0,n) F(s,max(0LL,x-(n-p)),min((int)x,p)){
			if(s<x) chkmax(ans,calc(p,s,0,0));
			if(s)chkmax(ans,calc(p,s,1,0));
			if(s)chkmax(ans,calc(p,s,1,1));
		}
	}else {
		F(t,0,k/n){
			solve(t+1,t,k-t*x-x-t*y,0);
			solve(t+1,t,k-t*x-x-t*y+1,1);
		}
	}
	write(ans);
	return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

//    if (K < Q) {
//        cout << "-1\n";
//        return;
//    }

    ll ans = -1;
//    if (K <= 2*Q) {
//        cout << min(N, K-Q + 1 + (N-Q)) << endl;
//        return;
//    }

    auto check = [&](ll rev, ll take) {
        ll s = take - N;
        ll left = (K - Q) - rev * take;
        if (take >= N && take <= 2*N && left >= 0 && left <= min(Q,s) && min(Q, left + 1) + (N - Q) >= s)
            ans = max(ans, s);
    };

    for (ll rev = 0; rev <= 1000000; ++rev) {
        check(rev, (K-Q+N + N-Q+1)/(rev+1));
    }

    for (ll take = N; take <= 1000000; ++take) {
        check((K - 2*Q) / take, take);
        check((K - 2*Q) / take + 1, take);
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,x,k,lb,ub,ans=-1;
int main() {
	ll l,r;
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	x=(r>=l?r-l+1:r+n-l+1)%n;
	for(ll i=k,j,r;i;i=j){
		j=k/(k/i+1);r=k/i;
		ub=min(2*n,i);
		lb=max(n,j+1);
		ub=min(ub,min((2*n+k-2*x+1)/(r+1),(k-x)/r));
		lb=max(lb,(k-2*x+r-1)/r);
		if(ub>=lb)ans=max(ans,ub);
	}
	if(x<=k&&k<=x*2)ans=max(ans,n+min(k-x,x-1)+n-x+1);
	if(!x&&k==n)ans=max(ans,n+1);
	printf("%lld\n",~ans?ans-n:ans);
}

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define REP(i,a,b) for(int i=(a),_end_=(b);i<=_end_;i++)
#define DREP(i,a,b) for(int i=(a),_end_=(b);i>=_end_;i--)
#define EREP(i,a) for(int i=start[(a)];i;i=e[i].next)
template<class T>inline void chkmax(T &a,T b){ if(a<b)a=b;}
template<class T>inline void chkmin(T &a,T b){ if(a>b)a=b;}
inline int read()
{
	int sum=0,p=1;char ch=getchar();
	while(!(('0'<=ch && ch<='9') || ch=='-'))ch=getchar();
	if(ch=='-')p=-1,ch=getchar();
	while('0'<=ch && ch<='9')sum=sum*10+ch-48,ch=getchar();
	return sum*p;
}

ll n,k,l,r,x;

inline void init()
{
	cin>>n>>l>>r>>k;
	if(l<=r)x=r-l+1;
	else x+=n-l+1+r;
}

inline void doing1()
{
	for(ll p=2*n;p>=n;p--)
	{
		ll t=(k-1)%p+1;
		if(x<=t && t<=x*2)
		{
			if((t-x+n<=p && p<=2*n-(2*x-t)) || ((t+1-x+n<=p && p<=2*n-(2*x-t-1))))printf("%lld\n",p-n),exit(0);
		}
	}
	puts("-1");
}

inline void doing2()
{
	ll ans=-n;

	if(x<=k && k<=2*x)printf("%lld\n",min(k-x+1+(n-x),n)),exit(0);

	for(ll i=1,lim=k/n;i<=lim;i++)
	{
		ll L=(k-2*x+i-1)/i,R=(k-x)/i;
		chkmax(L,n); chkmin(R,2*n);
		chkmax(L,(k-x+n+i)/(i+1)); chkmin(R,(2*n-2*x+k+1)/(i+1));
		if(L<=R)chkmax(ans,R);
	}
	if(ans<0)puts("-1");
	else printf("%lld\n",ans-n);
}

int main()
{
	init();
	if(n<=k/n)doing1();
	else doing2();
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,l,r,m,s,a,b,ans,M;
void merge(int &L,int &R,int x,int y){
	L=max(L,x);
	R=min(R,y);
}
int chu(int x,int y){
	return x>=0?x/y:x/y-!!(x%y);
}
signed main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&m);
	ans=-1;
	if (l<=r)s=r-l+1;
	else s=n-l+1+r;
	if (m<s){
		puts("-1");
		return 0;
	}
	if (m-s<=s)ans=max(ans,m-s+n-s);
	M=m-s;
	for (int i=n,j;i<=min(M,2*n);i=j+1){
		int k=M/i;j=M/k;
		a=M-k*n,b=-(M-k*n);
		if (!a){ans=max(ans,0ll);continue;}
		int L=(a-s)/k+!!((a-s)%k),R=a/k;
		merge(L,R,-b/(k+1)+!!(-b%(k+1)),chu(n-s-b,k+1));
		if (L<=R)ans=max(ans,R);
	}
	m++;
	if (m-s<=s)ans=max(ans,m-s+n-s);
	M=m-s;
	for (int i=n,j;i<=min(M,2*n);i=j+1){
		int k=M/i;j=M/k;
		a=M-k*n,b=-(M-k*n);
		if (!a)continue;
		int L=(a-s)/k+!!((a-s)%k),R=(a-1)/k;
		merge(L,R,-b/(k+1)+!!(-b%(k+1)),chu(n-s-b,k+1));
		merge(L,R,i-n,j-n);
		if (L<=R)ans=max(ans,R);
	}
	printf("%lld\n",ans);
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll n,m,l,r,i,j,x,ans=-1;
void work(ll x)
{
	if(x>n&&x<=2*n)ans=max(ans,x-n);
}
int main()
{
	cin>>n>>l>>r>>m;
	r=(r-l+1+n)%n;
	if(m<r)
	{
		puts("-1");
		return 0;
	}
	for(i=n;i<=m&&i<=2*n;i=j+1)
	{
		j=min(2*n,m/(m/i));
		x=min(2*n,min((m-r)/(m/i),(m+2*n-2*r+1)/(m/i+1)));
		if(x>=i&&m-m/i*x<=r+min(r,x-n))ans=x-n;
	}
	if(!r)for(i=1;i*i<=m+1;i++)if((m+1)%i==0)
	{
		work(i);
		work((m+1)/i);
	}
	if(m>=r&&m<=2*r)ans=max(ans,m+(m<2*r)+n-2*r);
	cout<<ans<<endl;
	return 0;
}

#include<bits/stdc++.h>
#define reg register int
#define il inline
#define fi first
#define se second
#define mk(a,b) make_pair(a,b)
#define numb (ch^'0')
#define pb push_back
#define solid const auto &
#define enter cout<<endl
#define pii pair<int,int>
using namespace std;
#define int long long
typedef long long ll;
template<class T>il void rd(T &x){
    char ch;x=0;bool fl=false;
    while(!isdigit(ch=getchar()))(ch=='-')&&(fl=true);
    for(x=numb;isdigit(ch=getchar());x=x*10+numb);
    (fl==true)&&(x=-x);
}
template<class T>il void output(T x){if(x/10)output(x/10);putchar(x%10+'0');}
template<class T>il void ot(T x){if(x<0) putchar('-'),x=-x;output(x);putchar(' ');}
template<class T>il void prt(T a[],int st,int nd){for(reg i=st;i<=nd;++i) ot(a[i]);putchar('\n');}
#define dh dghfgh
namespace Miracle{
ll n,l,r,k;
ll len;
ll che(ll i,ll M){
    // cout<<" che "<<i<<" "<<M<<endl;
    ll ret=-1;
    if(i==0){
        ll p=M;
        if(p<=len) ret=max(ret,p+n-len);
        p=M+1;
        if(p>=1&&p<=len) ret=max(ret,p+n-len);
    }
    else{
        ll p=M%i;
        ll ans=(M-p)/i;
        if(ans>n) {
            p+=(ans-n)*i;
            ans=n;
        }
        if(ans>n-len+p){
            ll tmp=(ans-(n-len+p)+i)/(i+1);
            ans-=tmp;
            p+=tmp*i;
        }
        if(p>=0&&p<=min(ans,len)) ret=max(ret,ans);

        p=(M+1)%i;
        ans=(M+1-p)/i;
        if(ans>n){
            p+=(ans-n)*i;
            ans=n;
        }
        if(ans>n-len+p){
            ll tmp=(ans-(n-len+p)+i)/(i+1);
            ans-=tmp;
            p+=tmp*i;
        }
        if(p>=1&&p<=min(ans,len)) ret=max(ret,ans);
    }
    // cout<<" ret "<<ret<<endl;
    return ret;
}
int main(){
    rd(n);rd(l);rd(r);rd(k);
    if(l<=r) len=r-l+1;
    else len=n-l+1+r;
    // cout<<" len "<<len<<endl;
    if(n<=2e6){
        ll ans=0;
        for(ans=n;ans>=0;--ans){
            ll r=k%(ans+n);
            if(r==0) r+=ans+n;
            int p=r-len;
            if(p>=max((ll)0,ans-(n-len))&&p<=min(ans,len)) break;
            r=(k+1)%(ans+n);
            p=r-len;
            if(p>=max((ll)1,ans-(n-len))&&p<=min(ans,len)) break;
        }
        if(ans>=0) printf("%lld",ans);
        else printf("-1");
    }else{
        ll M=k-len;
        ll ans=-1;
        for(ll i=0;M>=0;++i,M-=n){
            ll ret=che(i,M);
            ans=max(ans,ret);
        }
        printf("%lld",ans);
    }
    return 0;
}

}
signed main(){
    Miracle::main();
    return 0;
}

/*
   Author: *Miracle*
*/

#include<bits/stdc++.h>
using namespace std;

#define ll long long
namespace exgcd{
  ll gao(ll a,ll b,ll &x,ll &y){
    if (b==0){
      x=1; y=0; return a;
    }
    ll k=gao(b,a%b,x,y);
    ll t=x; x=y; y=t-a/b*y;
    return k;
  }
  bool fuck(ll a,ll b,ll c,ll lx,ll ly,ll &x,ll &y){
    ll g=gao(a,b,x,y);
    if (c%g) assert(0);
    a/=g; b/=g; c/=g;
    x*=c; y*=c;
    x=x%b-b-b+lx/b*b;
    while (x+b<=lx) x+=b; if (x<0) return 0;
    y=(c-a*x)/b;
    if (y>=0&&y<=ly) return 1;
    if (y>ly) return 0;
    ll d=(abs(y)+a-1)/a;
    y+=d*a; x-=d*b;
    return x>=0&&x<=lx&&y>=0&&y<=ly;
  }
}

ll n, d, k, x, y, ans=-1;

void doit(ll t){
  if (t<0) return;
  if (t==0){
    if (k>=d&&k<=2*d){
      ans=max(ans,(k-d==d? d: k-d+1)+n-d);
    }
    return;
  }
  ll aim=k-t*n-d;
  if (exgcd::fuck(t,t+1,aim,n-d,d,x,y)){
    ans=max(ans,x+y);
  }
}

void doit2(ll t){
  if (t<=0) return;
  ll aim=k-t*n-d;
  if (exgcd::fuck(t,t+1,aim,n-d,d,x,y)){
    if (!y) x-=t+1, y+=t;
    if (x>=0&&x<=n-d&&y>=0&&y<=d){
      ans=max(ans,x+y);
    }
  }
}

int main(){
  cin>>n>>x>>y>>k;
  d= y>=x? y-x+1: y+n-x+1;
  doit(0);
  for (ll i=n, nex;i<=n*2;i=nex+1){
    ll t=k/i; nex= t==0? 1e18: k/t;
    doit(t-1); doit(t); doit(t+1);
  }
  ++k;
  for (ll i=n, nex;i<=n*2;i=nex+1){
    ll t=k/i; nex= t==0? 1e18: k/t;
    doit2(t-1); doit2(t); doit2(t+1);
  }
  cout<<ans<<endl;
}

#include<bits/stdc++.h>
#define ll long long
#define ull unsigned ll
#define uint ungigned
#define db double
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pli pair<ll,int>
#define vi vector<int>
#define vpi vector<pii >
#define IT iterator

#define PB push_back
#define MK make_pair
#define LB lower_bound
#define UB upper_bound
#define y1 wzpakking
#define fi first
#define se second
#define BG begin
#define ED end

#define For(i,j,k) for (int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for (int i=(int)(j);i>=(int)(k);i--)
#define UPD(x,y) (((x)+=(y))>=mo?(x)-=mo:233)
#define CLR(a,v) memset(a,v,sizeof(a))
#define CPY(a,b) memcpy(a,b,sizeof(a))
#define sqr(x) (1ll*x*x)

#define LS3 k*2,l,mid
#define RS3 k*2+1,mid+1,r
#define LS5 k*2,l,mid,x,y
#define RS5 k*2+1,mid+1,r,x,y
#define GET pushdown(k);int mid=(l+r)/2
#define INF (1<<29)
using namespace std;
ll n,l,r,k,ans=-1;
void checkok(ll val2,ll val1,ll fi,ll se,ll pre){
	val2=val2-val1;
	se=se-fi;
	if (!(fi+pre<=val1&&val1<=2*fi)) return;
	if (!(se<=val2&&val2<=2*se)) return;
	ans=max(ans,val1+val2-fi-se);
}
void check1(ll val){
	checkok(val,(k+val-1)%val+1,r,n,0);
	checkok(val,k%val+1,r,n,1);
}
pll getrange(ll lv,ll k,ll mv,ll rv){
	lv-=mv; rv-=mv;
	if (!k){
		if (lv<=0&&rv>=0) return pll(0,1ll<<60);
		return pll(-1,-1);
	}
	if (k<0){
		swap(lv,rv);
		lv=-lv; rv=-rv;
		k=-k;
	}
	if (rv<0) return pll(-1,-1);
	if (lv<0) lv=max(lv,0ll);
	return pll((lv+k-1)/k,rv/k);
}
pll merge(pll a,pll b){
	if (a.fi==-1||b.fi==-1) return pll(-1,-1);
	if (a.se>b.se) swap(a,b);
	if (a.se<b.fi) return pll(-1,-1);
	return pll(max(a.fi,b.fi),a.se);
}
void check2(ll round){
	if (round==0){
		if (r<=k&&k<=2*r) ans=max(ans,n-r+k-r);
		if (r+1<=k+1&&k+1<=2*r) ans=max(ans,n-r+(k+1-r));
		return;
	}
	ll r=min(k/round,2*n);
	ll l=max(k/(round+1)+1,n);
	ll fi=::r,se=n-::r;
	if (l<=r){
		pll range1=getrange(fi+1,-round,k+1,2*fi);
		pll range2=getrange(se,round+1,-k-1,2*se);
		pll range=merge(pll(l,r),merge(range1,range2));
		if (range.fi!=-1) ans=max(ans,range.se-n);
	}
	r=min((k-1)/round,2*n);
	l=max((k-1)/(round+1)+1,n);
	if (l<=r){
		pll range1=getrange(fi,-round,k,2*fi);
		pll range2=getrange(se,round+1,-k,2*se);
		pll range=merge(pll(l,r),merge(range1,range2));
		if (range.fi!=-1) ans=max(ans,range.se-n);
	}
}
//checkok(val,k-round*val+1,r,n,1)
//val2=(round+1)*val-k-1
//val1=k-round*val+1
//fi+1<=round<=2*fi

//checkok(val,k-round*val,r,n,1)
//val2=(round+1)*val-k
//val1=k-round*val
//fi<=round<=2*fi
int main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	r=(r-l+n)%n+1;
	if (n<=200000)
		for (ll i=n;i<=2*n;i++) check1(i);
	else
		for (ll round=k/(2*n);round<=k/n;round++)
			check2(round);
	printf("%lld",ans);
}

#include<bits/stdc++.h>
using namespace std;

#define F(i,a,b) for(int i=a;i<=b;i++)
#define D(i,a,b) for(int i=a;i>=b;i--)
#define ms(i,a)  memset(a,i,sizeof(a))
#define LL       long long
template<class T>void read(T &x){
	x=0; char c=getchar();
	while (c<'0' || c>'9') c=getchar();
	while (c>='0' && c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
}
template<class T>void write(T x){
	if(x<0) x=-x,putchar('-');
	if(x>9) write(x/10);
	putchar(48+x%10);
}
template<class T>void chkmax(T &x,T y){ x=x>y? x:y; }
LL n,k,l,r,x,t,s,p,ans,y;
LL const inf=1LL<<50;
LL calc(LL p,LL s,int a,int b){
	if(a==0 || b==1){
		if(k-s-x>=0 && (k-s-x)%(n+p)==0)
			return p;
		else return -1;
	}else {
		if(k-s+1-x>=0 && (k-s+1-x)%(n+p)==0)
			return p;
		else return -1;
	}
}

LL exgcd(LL &x,LL &y,LL a,LL b){
	if(!b){
		x=1;y=0; return a;
	}
	LL t=exgcd(y,x,b,a%b);
	y-=a/b*x;
	return t;
}
void solve(LL t1,LL t2,LL c,LL add){
	if(t2==0){
		if(2*x>=k && k>=x) chkmax(ans,min(x,k-x+1)+y);
		return;
	}
	LL a,b;
	LL g=exgcd(a,b,t1,t2);
	a=a*c; b=b*c;
	LL l=-inf,r=inf;
	a-=add;
	if (a>=0) r=min(r,a/t2); else  r=min(r,(a-t2+1)/t2); a+=add;
	if(a-x>=0) l=max(l,(a-x+t2-1)/t2); else l=max(l,(a-x)/t2);
	if(y-b>=0) r=min(r,(y-b)/t1); else r=min(r,(y-b-t1+1)/t1);
	if(-b>=0) l=max(l,(-b+t1-1)/t1); else l=max(l,-b/t1);
	if(l<=r){
		chkmax(ans,a+b+l);
		chkmax(ans,a+b+r);
	}
}
int main(){
	read(n);
	read(l);
	read(r);
	read(k);
	x=(r-l+n)% n+1;
	y=n-x;
	ans=-1;
	if(k/n>5000000){
		F(p,0,n) F(s,max(0LL,x-(n-p)),min((int)x,p)){
			if(s<x) chkmax(ans,calc(p,s,0,0));
			if(s)chkmax(ans,calc(p,s,1,0));
			if(s)chkmax(ans,calc(p,s,1,1));
		}
	}else {
		F(t,0,k/n){
			solve(t+1,t,k-t*x-x-t*y,0);
			solve(t+1,t,k-t*x-x-t*y+1,1);
		}
	}
	write(ans);
	return 0;
}

//#pragma GCC optimize("O3")
//#pragma GCC target("arch=corei7-avx")
#include <bits/stdc++.h>
#ifndef ONLINE_JUDGE
# include <sys/time.h>
# include <sys/resource.h>
#endif

/*** TEMPLATE CODE STARTS HERE ***/

#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795028841971693993751
#endif

using namespace std;

typedef vector<string> vs;
typedef long long ll;
typedef complex<double> pnt;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

#define RA(x) begin(x), end(x)
#define FE(i, x) for (auto i = begin(x); i != end(x); ++i)
#define SZ(x) ((ll) (x).size())

template<class T>
void splitstr(const string &s, vector<T> &out)
{
    istringstream in(s);
    out.clear();
    copy(istream_iterator<T>(in), istream_iterator<T>(), back_inserter(out));
}

template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }

static void redirect(int argc, const char **argv)
{
#ifndef ONLINE_JUDGE
    struct rlimit rlim;
    getrlimit(RLIMIT_STACK, &rlim);
    rlim.rlim_cur = 256 * 1024 * 1024;
    setrlimit(RLIMIT_STACK, &rlim);
#ifndef __SANITIZE_ADDRESS__
    getrlimit(RLIMIT_DATA, &rlim);
    rlim.rlim_cur = 256 * 1024 * 1024;
    setrlimit(RLIMIT_DATA, &rlim);
#endif
#endif

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    if (argc > 1)
    {
        static filebuf f;
        f.open(argv[1], ios::in);
        cin.rdbuf(&f);
        if (!cin)
        {
            cerr << "Failed to open '" << argv[1] << "'" << endl;
            exit(1);
        }
    }

    if (argc > 2)
    {
        static filebuf f;
        f.open(argv[2], ios::out | ios::trunc);
        cout.rdbuf(&f);
        if (!cout)
        {
            cerr << "Failed to open '" << argv[2] << "'" << endl;
        }
    }
}

/*** TEMPLATE CODE ENDS HERE */

int main(int argc, const char **argv)
{
    redirect(argc, argv);
    ll n, l, r, k;
    cin >> n >> l >> r >> k;
    ll q = (r - l + n) % n + 1;
    k -= q;
    ll ans = -1;
    if (k >= 0 && k <= q)
        ans = min(k + 1, q) + (n - q);
    for (ll pass = 0; pass < 2; pass++)
    {
        for (ll i = 1; i * i <= k; i++)
        {
            ll s = (k - pass) / i - n;
            s = min(s, (k - i * n + n - q) / (i + 1));
            if (s >= 0 && s <= n)
            {
                ll t = k - i * (n + s);
                if (t >= pass && t <= q && t <= s && s - t <= n - q)
                    ans = max(ans, s);
            }

            if (i >= n && i <= 2 * n)
            {
                s = i - n;
                ll lo = max(pass, s - (n - q));
                ll w = (k - lo) / (n + s);
                ll t = k - w * (n + s);
                if (t >= pass && t <= q && t <= s && s - t <= n - q)
                    ans = max(ans, s);
            }
        }
        k++;
    }
    cout << ans << '\n';

    return 0;
}

#include <bits/stdc++.h>
using namespace std;

int main(){
    int64_t i, j, k;
    int64_t N, L, R, K;
    cin >> N >> L >> R >> K;
    R = (R-L+N) % N + 1;

    if(N <= 1e6){
        for(i=N; i>=0; i--){
            int64_t d = N+i;
            int64_t m = (d+K-R-min(i, R)-1)/d-1;
            int64_t M = (d+K-R-max(R-(N-i+1), 0LL))/d-1;
            if(M > m){
                cout << i << endl;
                return 0;
            }
        }
    }else{
        for(i=0; i<=(N+K-R)/N-1; i++){
            int64_t d = i+1;
            int64_t s = K-i*N-R;
            int64_t s2 = s-R+N+1;
            int64_t m = (d+s-1)/d-1;
            int64_t M = min(N, (d+s2)/d-1);
            if(i > 0) M = min(M, s/i);
            if(i > 0) m = max(m, (i+s-R-1)/i-1);
            if(M > m){
                cout << M << endl;
                return 0;
            }
        }
    }
    cout << -1 << endl;
    return 0;
}

#include"bits/stdc++.h"
using namespace std;

long long int n;
long long int l;
long long int r;
long long int k;

pair<long long int, long long int> calc(long long int sm, long long int len) {
	long long int two = (sm - len);
	return make_pair(len - two, two);
}

pair<long long int,long long int> S(long long int val, long long int unit, long long int lef, long long int rig) {
	long long int cong = (val%unit)+unit;
	cong %= unit;
	if (rig < cong) {
		return make_pair(1, -1);
	}
	long long int want = cong + unit - (lef%unit);
	want %= unit;
	lef += want;
	want = (rig%unit)-cong+unit;
	want %= unit;
	rig -= want;

	/*lef = max(lef, cong);
	long long int R = rig;
	long long int L = lef;
	lef -= cong;
	rig -= cong;
	lef = ((lef + unit - 1) / unit) * unit;
	rig = (rig / unit)*unit;
	lef += cong;
	rig += cong;*/
	return make_pair(lef, rig);
}
int main() {
	cin >> n >> l >> r >> k;
	long long int len = r + n - l+1LL;
	long long int ot = n - len;
	len %= n;
	long long int maxi = -1;
	if (n <= 1000000) {
		for (long long int periphery = n; periphery <= 2LL * n; periphery++) {
			long long int f = k / periphery;
			long long int md = k % periphery;
			if (md < len) {
				continue;
			}
			if (md > len * 2LL) {
				continue;
			}
			auto overall = calc(periphery, n);
			auto rest = calc(md, len);
			if (rest.first > overall.first) {
				rest.first--;
				rest.second++;
			}
			if (rest.first <= overall.first&&rest.second <= overall.second) {
				//if (overall.first-rest.first+overall.second-rest.second==ot) {
					maxi = max(maxi, overall.second);
				//}
			}
		}
		printf("%lld\n", maxi);
		return 0;
	}
	if (k < len) {
		puts("-1");
		return 0;
	}
	if (len == 0) {
		len = n;
	}
	if(len*2LL>=k){
		auto z = calc(k, len);
		if (z.first) {
			z.second++;
		}
		maxi = max(maxi, z.second+(n-len));
	}
	len %= n;
	//%peri    mod>=(len)
	for (long long int i = 1; i <= 1000000; i++) {
		long long int walk = i * n + len;
		long long int R = k - walk;
		if (R < 0)continue;
		//i*a+(i+1)*b=R
		//ext gcd
		//a=b=R
		long long int lcm = i * (i + 1);
		long long int unit_a = lcm / i;
		long long int unit_b = lcm / (i + 1);
		auto ap = S(-R, unit_a, 0, n - len);
		auto ap2 = S(R, unit_b, 0, len);
		if (ap.first > ap.second || ap2.first > ap2.second)continue;
		ap2.first = (R - (i + 1)*ap2.first) / i;
		ap2.second = (R - (i + 1)*ap2.second) / i;
		if (ap2.first > ap2.second)swap(ap2.first, ap2.second);
		long long int lef = max(ap.first, ap2.first);
		long long int rig = min(ap.second, ap2.second);
		if (lef > rig)continue;
		maxi = max(maxi, lef + (R - lef * i) / (i + 1));
		maxi = max(maxi, rig + (R - rig * i) / (i + 1));
	}
	long long int vis = 0;
	for (long long int i = 1; i <= 1000000; i++) {
		long long int walk = i * n + len;
		long long int R = k - walk+1LL;
		if (R < 0)continue;
		//i*a+(i+1)*b=R
		//ext gcd
		//a=b=R
		long long int lcm = i * (i + 1);
		long long int unit_a = lcm / i;
		long long int unit_b = lcm / (i + 1);
		auto ap = S(-R, unit_a, 0, n - len);
		auto ap2 = S(R, unit_b, 1, len);
		if (ap.first > ap.second || ap2.first > ap2.second)continue;
		ap2.first = (R - (i + 1)*ap2.first) / i;
		ap2.second = (R - (i + 1)*ap2.second) / i;
		if (ap2.first > ap2.second)swap(ap2.first, ap2.second);
		long long int lef = max(ap.first, ap2.first);
		long long int rig = min(ap.second, ap2.second);
		if (lef > rig)continue;
		maxi = max(maxi, lef + (R - lef * i) / (i + 1));
		maxi = max(maxi, rig + (R - rig * i) / (i + 1));
	}
	printf("%lld\n", maxi);
	return 0;
}

#include<cstdio>
//in: a,x out: b,y
//x+a+t(n+a+b) = k
long long partOne(long long n,long long l,long long r,long long k,int mode){
    long long res = -1;
    long long x = -1;
    if(r>=l) x = r-l+1;
    else x = n-l+1+r;
    long long y = n-x;
    //printf("x = %lld, y = %lld\n",x,y);
    long long sa = 0;
    if(mode) sa = 1;
    for(long long a = sa; a <= x; a++){
        for(long long b = 0; b <= y; b++){
            long long left = k-x-a;
            long long cycle = n+a+b;
            if(left>=0 && left%cycle==0){
                long long offer = a+b;
                if(res<offer) res = offer;
            }
        }
    }
    return res;
}

void exGcd(long long a,long long b,long long& x,long long& y){
    if(b==0) x = 1, y = 0;
    else{
        exGcd(b,a%b,x,y);
        long long t = x;
        x = y;
        y = t-(a/b)*x;
    }
}

//c <= k*mul minK
long long getLower(long long mul,long long c){
    if(c%mul==0) return c/mul;
    else{
        if(c>=0) return (c/mul)+1;
        else{
            long long res = (-c)/mul;
            return -res;
        }
    }
}
//k*mul <= c maxK
long long getUpper(long long mul,long long c){
    if(c%mul==0) return c/mul;
    else{
        if(c>=0) return c/mul;
        else{
            long long res = (-c)/mul;
            return -res-1ll;
        }
    }
}

//upper
//mode = lowerU
//cx0+kcb, cy0-kca
long long solveEq(long long a,long long b,long long c,long long ux,long long uy,int mode){
    long long x0,y0;
    exGcd(a,b,x0,y0);
    long long lower = 0-c*x0;
    if(mode) lower++;
    long long minK = getLower(b,lower);
    long long maxK = getUpper(b,ux-c*x0);
    long long resK = getLower(a,c*y0-uy);
    if(minK<resK) minK = resK;
    resK = getUpper(a,c*y0);
    if(maxK>resK) maxK = resK;
    if(minK<=maxK){
        long long take = -1;
        if(b>=a) take = maxK;
        else take = minK;
        return c*(x0+y0)+take*(b-a);
    }
    else return -1;
}

//be careful on last one is 2 but pick 1
//x+a+t(n+a+b) = k
long long partTwo(long long n,long long l,long long r,long long k,int mode){
    long long res = -1;
    long long x = -1;
    if(r>=l) x = r-l+1;
    else x = n-l+1+r;
    long long y = n-x;
    for(long long t = 1; t*n <= k; t++){
        long long c = k-t*n-x;
        long long offer = -1;
        if(c<0) offer = -1;
        else if(c==0){
            if(!mode) offer = 0;
            else offer = -1;
        }
        else offer = solveEq(t+1,t,c,x,y,mode);
        //printf("%lld %lld %lld %lld %lld\n",t+1,t,c,x,y);
        if(res<offer) res = offer;
        //printf("t = %lld, offer = %lld\n",t,offer);
    }
    //sp judge on t = 0
    if(x<=k){
        long long a = k-x;
        if(a<=x && a>=mode){
            long long b = y;
            if(res<a+b) res = a+b;
        }
    }
    return res;
}

int main(){
    long long up = 10000;
    long long n,l,r,k;
    scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
    //printf("%lld\n",partOne(n,l,r,k,0));
    //printf("%lld\n",partOne(n,l,r,k+1,1));
    //printf("%lld\n",partTwo(n,l,r,k,0));
    //printf("%lld\n",partTwo(n,l,r,k+1,1));
    long long ans = -1; long long res = -1;
    if(n<=up){
        res = partOne(n,l,r,k,0);
        if(ans<res) ans = res;
        res = partOne(n,l,r,k+1,1);
        if(ans<res) ans = res;
    }
    else{
        res = partTwo(n,l,r,k,0);
        if(ans<res) ans = res;
        res = partTwo(n,l,r,k+1,1);
        if(ans<res) ans = res;
    }
    printf("%lld\n",ans);
    return 0;
}

/*
    Editorial solution : https://codeforces.com/blog/entry/62455
*/

#include <bits/stdc++.h>

typedef long double ld ;
#define long long long int
using namespace std;
#define mp make_pair
#define pb push_back
#define INF 1e18
#define INF2 1e9
// #define pi 3.141592653589
#define x first
#define y second
// #define endl "\n"

long cons;
long check(long a)
{
    if(a>=cons)a%=cons;
    return a;
}
long check2(long a)
{
	a%=cons;
	if(a<0)
		a+=cons;
	return a;
}

long fast_check(long a)
{
	if(a>=cons)
		a-=cons;
	return a;
}

long GCD(long a,long b)
{
	while(a && b)
	{
		a=a%b;
		if(a!=0)
			b=b%a;
	}
	return a+b;
}

long exp(long a,long n)
{
	long ans=1;
	a=check(a);
	while(n)
	{
		if(n&1)
			ans=check(ans*a);
		a=check(a*a);
		n=(n>>1);
	}
	return ans;
}

void print_pair(pair<int,int> p)
{
	cout<<p.x<<" "<<p.y<<endl;
}

long nc2(long a)
{
	return (a*(a-1))/2;
}

const int N=2002;
// const int M=2001;
long n,l,r,s;
long ans=-1;
long term;
long other;

bool consistent(long t,long rem)
{
	if(rem>t)
		return false;
	t-=rem;
	if(other<t)
		return false;
	return true;
}

void solve1()
{
	if(s<0)
		return;
	for(long t=0;t<=n;t++)
	{
		long rem=s%(n+t);
		// if(rem<term)
		// 	rem++;
		// cout<<t<<" "<<rem<<endl;
		if(rem<=term && consistent(t,rem))
		{
			// cout<<"Yay"<<endl;
			ans=max(ans,t);
			continue;
			// cout<<ans<<endl;
		}
		rem++;
		if(rem<=term && consistent(t,rem))
		{
			// cout<<"Yay"<<endl;
			ans=max(ans,t);
			continue;
			// cout<<ans<<endl;
		}

	}
}

void solve2()
{
	if(s<0)
		return;
	long max_cycle=s/n;
	if(s<=term)
	{
		if(s<term)
			s++;
		ans=s+other;
		return;
	}
	// cout<<max_cycle<<endl;
	for(long k=1;k<=max_cycle;k++)
	{
		// cout<<k<<endl;
		long it_rem=s-k*n;

		long maxt=it_rem/k;
		long mint=it_rem/(k+1);
		long bestt=-1;

		while(mint<=maxt)
		{
			long mid=(mint+maxt)/2;
			long rem=it_rem-k*mid;
			if(rem>term)
			{
				mint=mid+1;
				continue;
			}

			if(rem<=mid && mid-rem<=other)
			{
				bestt=mid;
				mint=mid+1;
				continue;
			}
			rem++;
			if(rem<=mid && mid-rem<=other)
			{
				bestt=mid;
				mint=mid+1;
				continue;
			}
			else
				maxt=mid-1;
		}

		if(bestt!=-1)
			ans=max(ans,bestt);

		// long rem=s%k;
		// cout<<t<<" "<<rem<<endl;
		// // if(rem<term)
		// // 	rem++;
		// if(rem<=term && consistent(t,rem))
		// {
		// 	ans=max(ans,t);
		// 	continue;
		// }
		// rem++;
		// if(rem<=term && consistent(t,rem))
		// {
		// 	ans=max(ans,t);
		// 	continue;
		// }
	}
}

int main()
{
	ios::sync_with_stdio(false);cin.tie(0);
	cons=1e9+7;
	srand(time(NULL));
	// freopen("evaluations.in","r",stdin);
	cin>>n>>l>>r>>s;

	if(l>r)
		term=n-(l-r-1);
	else
		term=r-l+1;
	s-=term;

	other=n-term;

	if(n<=5*1000000)
		solve1();
	else
		solve2();
	cout<<ans;

	return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int rd(){int s=0,c,b=0;while(((c=getchar())<'0'||c>'9')&&c!='-');if(c=='-'){c=getchar();b=1;}do{s=s*10+c-'0';}while((c=getchar())>='0'&&c<='9');return b?-s:s;}
void put(int x){if(!x){putchar('0');return;}static int c[20];int t=0;while(x){c[++t]=x%10;x/=10;}while(t)putchar(c[t--]+'0');}
ll n,k,l,r,ans=-1,len;
int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
    len=(r>=l?r-l+1:n-l+1+r);
    if(n<=1000000)
        for(int i=n;i<=2*n;i++)
        {
            ll s=k%i;
            if(s==0)s=i;
            s-=len;
            ll mi=max(i-n-(n-len)-1,0ll);
            ll ma=min(len,i-n);
            if(s>=mi&&s<=ma)
                ans=max(ans,i-n);
        }
    else
    {
        if(k>=len&&k<=2*len)
            ans=max(ans,k==2*len?n:n-len+k-len+1);
        for(int i=1;i<=k/n;i++)
        {
            ll s2=min((k-2*len+2*n+1)/(i+1),(k-len)/i);
            ll s1=max((k-2*len+i-1)/i,(k-len+n+i)/(i+1));
            if(s1<=s2)
                ans=max(ans,s2-n);
        }
    }
    printf("%lld\n",ans);
    return 0;
}

#include<bits/stdc++.h>
#define rep(i,x,y) for (int i=(x);i<=(y);i++)
#define ll long long
using namespace std;
ll n,l,r,m,s,a,b,ans,M;
void merge(ll &L,ll &R,ll x,ll y){ L=max(L,x); R=min(R,y); }
ll chu(ll x,ll y){ return x>=0?x/y:x/y-!!(x%y); }
int main(){
	cin>>n>>l>>r>>m; ans=-1;
	if (l<=r) s=r-l+1; else s=n-l+1+r;
	if (m<s) return puts("-1"),0;
	if (m-s<=s) ans=max(ans,m-s+n-s);
	M=m-s;
	for (ll i=n,j;i<=min(M,2*n);i=j+1){
		ll k=M/i; j=M/k;
		a=M-k*n,b=-(M-k*n);
		if (!a){ ans=max(ans,0ll); continue; }
		ll L=(a-s)/k+!!((a-s)%k),R=a/k;
		merge(L,R,-b/(k+1)+!!(-b%(k+1)),chu(n-s-b,k+1));
		if (L<=R) ans=max(ans,R);
	}
	m++;
	if (m-s<=s) ans=max(ans,m-s+n-s);
	M=m-s;
	for (ll i=n,j;i<=min(M,2*n);i=j+1){
		ll k=M/i; j=M/k;
		a=M-k*n,b=-(M-k*n);
		if (!a) continue;
		ll L=(a-s)/k+!!((a-s)%k),R=(a-1)/k;
		merge(L,R,-b/(k+1)+!!(-b%(k+1)),chu(n-s-b,k+1));
		merge(L,R,i-n,j-n);
		if (L<=R) ans=max(ans,R);
	}
	cout<<ans;
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

const int max_n = -1;
const long long inf = 1000111222000111222LL;

long long n, l, r, k;
long long cnt;

long long triv(long long n, long long l, long long r, long long k) {
    long long ans = -1;
    for (long long x = 0; x <= n; ++x) {
        long long y = k % (n + x);
        if (cnt <= y && y <= 2 * cnt && x - n + 2 * cnt <= y && y <= x + cnt) {
            ans = max(ans, x);
        }
    }
    return ans;
}

long long triv2(long long n, long long l, long long r, long long k) {
    ++k;
    long long ans = -1;
    for (long long x = 1; x <= n; ++x) {
        long long y = k % (n + x);
        if (1 + cnt <= y && y <= 2 * cnt && x - n + 2 * cnt <= y && y <= x + cnt) {
            ans = max(ans, x);
        }
    }
    return ans;
}

void upd(long long &L, long long &R, long long C) {
    if (L > R) {
        L = 1;
        R = 0;
        return;
    }
    if (C == 0) {
        if (L <= 0 && R >= 0) {
            L = -inf;
            R = inf;
        } else {
            L = 1;
            R = 0;
        }
    } else {
        if (L < 0) {
            L = 0;
        } else {
            L = (L + C - 1) / C;
        }
        if (R < 0) {
            R = -1;
        } else {
            R = R / C;
        }
    }
}

void intersect(long long l1, long long r1, long long l2, long long r2, long long &l, long long &r) {
    if (l1 > r1 || l2 > r2) {
        l = 1;
        r = 0;
        return;
    }
    if (l1 > l2) {
        swap(l1, l2);
        swap(r1, r2);
    }
    if (r1 < l2) {
        l = 1;
        r = 0;
    } else {
        l = l2;
        r = min(r1, r2);
    }
}

long long solve(long long n, long long l, long long r, long long k, long long st) {
    k += st;
    long long lx = st, ans = -1;
    while (lx <= n) {
        long long C = k / (n + lx), rx;
        if (C == 0) {
            rx = n;
        } else {
            rx = k / C - n;
        }
        long long l1, r1, l2, r2;
        l1 = k - C * n - 2 * cnt;
        r1 = k - C * n - cnt;// - st; // #
        if (cnt != 0 && st == 1) {
            --r1;
        }
        l2 = k - C * n - cnt;
        r2 = k - C * n + n - 2 * cnt;
        upd(l1, r1, C);
        upd(l2, r2, C + 1);
        long long okl, okr;
        intersect(lx, rx, l1, r1, okl, okr);
        intersect(okl, okr, l2, r2, okl, okr);
        if (okl <= okr) {
            ans = okr;
        }
        //cout << lx << " " << rx << " " << C << ": " << okl << " " << okr << "    " << l1 << " " << r1 << " " << l2 << " " << r2 << endl;
        lx = rx + 1;
    }
    return ans;
}

int main() {
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    cin >> n >> l >> r >> k;
    cnt = (r - l + 1) % n;
    if (cnt < 0) {
        cnt += n;
    }
    /*if (cnt == 0) {
        // k : (n + x)
        long long ans = -1;
        for (long long i = 1; i * i <= k; ++i) {
            if (k % i == 0) {
                long long x;
                x = i - n;
                if (0 <= x && x <= n) {
                    ans = max(ans, x);
                }
                x = k / i - n;
                if (0 <= x && x <= n) {
                    ans = max(ans, x);
                }
            }
        }
        cout << ans << "\n";
        return 0;
    }*/
    //cout << triv(n, l, r, k) << endl;
    //cout << triv2(n, l, r, k) << endl;
    long long q = solve(n, l, r, k, 0);
    long long w = solve(n, l, r, k, 1);
    long long ans = max(q, w);
    cout << ans << "\n";
    return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

//    if (K < Q) {
//        cout << "-1\n";
//        return;
//    }

    ll ans = -1;
//    if (K <= 2*Q) {
//        cout << min(N, K-Q + 1 + (N-Q)) << endl;
//        return;
//    }

    auto check = [&](ll rev, ll take) {
        ll s = take - N;
        ll left = (K - Q) - rev * take;
        if (take >= N && take <= 2*N && left >= 0 && left <= min(Q,s) && min(Q, left + 1) + (N - Q) >= s)
            ans = max(ans, s);
    };

    for (ll rev = 0; rev <= 1000000; ++rev) {
        check(rev, (K-Q+N + N-Q+1)/(rev+1));
    }

    for (ll take = N; take <= min(2*N, 1000000LL); ++take) {
        check((K - 2*Q) / take, take);
        check((K - 2*Q) / take + 1, take);
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

#include <cstdio>
#include <cstring>
#include <algorithm>
#define int long long

using namespace std;

const int Lim = 1000000;

int n, l, r, k;

int check(int k) {
    int ans = -1;
    for(int i = 0; i <= Lim && i <= n; i++)
        if(k % (n + i) == 0) ans = max(ans, i);
    for(int i = 1; i <= Lim; i++)
        if(k % i == 0 && k / i <= n + n) ans = max(ans, k / i - n);
    return ans;
}

int bigeq(int x, int y) {
    int tmp = x / y;
    while(tmp * y < x) tmp++;
    while((tmp - 1) * y >= x) tmp--;
    return tmp;
}

int smalleq(int x, int y) {
    int tmp = x / y;
    while(tmp * y > x) tmp--;
    while((tmp + 1) * y <= x) tmp++;
    return tmp;
}

signed main() {
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    r = (r + n - l) % n + 1;
    l = 1;
    int ans = -1;
    if(r == n) {
        printf("%lld\n", max(check(k), check(k + 1)));
        return 0;
    }
    // Case 2
    for(int i = 0; i <= Lim && i <= n; i++) {
        int s = k % (n + i), j = s - r;
        if(0 <= j && j <= i && j <= r && i - j <= n - r) ans = max(ans, i);
        j = s - r;
        if(0 <= j && j < i && j < r && i - j - 1 <= n - r) ans = max(ans, i);
    }
    // Case 1
    for(int t = 0; t <= Lim; t++) {
        int k = ::k - t * n;
        int r1 = !t ? (k - r >= 0 ? n : -1) : smalleq(k - r, t);
        int r2 = smalleq(k + n + 1 - r - r, t + 1);
        int l1 = !t ? (k - r - r <= 0 ? 0 : n + 1) : bigeq(k - r - r, t);
        int l2 = bigeq(k - r, t + 1);
        int ll = max(l1, l2);
        int rr = min(r1, r2);
        if(ll <= rr) ans = max(ans, rr);
    }
    printf("%lld\n", ans);
    return 0;
}

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;

typedef long long ll;
ll n,pos,tot;

ll getr(ll l,ll r){
	ll slo=tot/l,res,mid;
	if(l>r)
		return 0;
	if(tot-slo*l<pos+max(0ll,l+pos-2ll*n-1))
		return 0;
	res=l;
	while(l<=r){
		mid=(l+r)>>1;
		if(tot-slo*mid>=pos+max(0ll,mid+pos-2ll*n-1)){
			res=mid;
			l=mid+1;
		}
		else
			r=mid-1;
	}
	return res;
}

int main(){
	ll i,j,l,r,ans,res,last;
	//freopen("a.in","r",stdin);
	//freopen("a.out","w",stdout);
	scanf("%lld%lld%lld%lld",&n,&l,&r,&tot);
	pos=r-l+1;
	if(pos<=0)
		pos+=n;
	if(pos==n){
		ans=-1;
		if(tot%n==0)
			ans=0;
		for(i=n;i<=tot;i=last+1){
			last=tot/(tot/i);
			if((tot%last==0)&&(last-n<=n))
				ans=last-n;
		}
		tot++;
		for(i=n;i<=tot;i=last+1){
			last=tot/(tot/i);
			if((tot%last==0)&&(last-n<=n))
				ans=max(ans,last-n);
		}
		if(tot-n<=n)
			ans=max(ans,tot-n);
		printf("%lld\n",ans);
		return 0;
	}
	ans=-1;
	for(i=n;i<=tot;i=last+1){
		last=tot/(tot/i);
		res=getr(i,last);
		if(res){
			if(tot%res<=min(2ll*pos,pos+res-n))
				ans=res-n;
		}
	}
	res=getr(tot+1,2ll*n);
	if(res){
		if(min(2ll*pos,pos+(res-n))>=tot)
			ans=res-n;
	}
	printf("%lld\n",ans);
	return 0;
}

#include <bits/stdc++.h>
using namespace std;

#define rep(n) for(int _ = 0; _ != (n); ++_)

namespace io{
    template<typename T> void println(const T &t) { cout << t << '\n'; }
    template<typename T, typename ...Args> void println(const T &t, const Args &...rest) { cout << t << ' '; println(rest...); }

    template<typename T> void print(const T &t) { cout << t << ' '; }

    template<typename T, typename ...Args> void print(const T &t, const Args &...rest) { cout << t; print(rest...); }

// this overload is chosen when there's only one argument
    template<class T> void scan(T &t) { cin >> t; }
    template<class T, class ...Args> void scan(T &a, Args &...rest) { cin >> a; scan(rest...); }
}
using namespace io;

using ll = long long;

// nonnegative less equal
ll ple(ll fz, ll fm) { // fz >= 0, fm > 0
    return fz / fm;
}
// nonnegative greater equal
ll pge(ll fz, ll fm) { //fz >= 0, fm > 0
    return (fz + fm - 1) / fm;
}

ll le (ll fz, ll fm) {
    return fz >= 0 ? ple(fz, fm) : -pge(-fz, fm); // 别忘了pge(-fz, fm)前面的负号！
}
ll ge(ll fz, ll fm) {
    return fz >= 0 ? pge(fz, fm) : -ple(-fz, fm);
}

int main() {
    ios::sync_with_stdio(false);
//    cin.tie(nullptr);
#ifdef LOCAL
    freopen("main.in", "r", stdin);
//    freopen("main.out", "w", stdout);
#endif

    ll n, l, r, k;
    cin >> n >> l >> r >> k;
    ll x = r - l + 1;
    if (x <= 0) x += n;
    ll y = n - x;
    ll ans = -1;

    if (n <= (ll)cbrt(k)) {
        for (ll a = 0; a <= x; a++) {
            for (ll b = 0; b <= y; b++) {
                ll s = a + x + b + y;
                ll bb = k - a - x;
                if (bb >= 0 && bb % s == 0) {
                    ans = max(ans, a + b);
                }
                if (a > 0 && (bb + 1) >= 0 && (bb+1)%s == 0) {
                    ans = max(ans, a + b);
                }
            }
        }
    }
    else {
        for (ll t = 0; t <= k / n; t++) {
            ll bb = k - n * t - x;
            if (bb >= 0) {
                // a = bb - tz , b = (t + 1) z - bb;
                if (t == 0) { // a = bb, b可任意取值
                    if (bb <= x) ans = max(ans, bb + y);
                    if (bb + 1 <= x) ans = max(ans, bb + 1 + y);
                }
                else {
                    // bb - tz >= 0 => z <= bb / t, bb - tz <= x => z >= (bb - x) / t
                    // (t + 1) z - bb >= 0 => z >= bb / (t + 1), (t + 1) z - bb <= y -> z <= (bb + y) / (t + 1)
                    ll minz = max(ge(bb - x, t), ge(bb, t + 1));
                    ll maxz = min(le(bb, t), le(bb + y, t + 1));
                    if (maxz >= minz) {
                        ans = max(ans, maxz);
                    }
                    // bb - tz >= 1 => z <= (bb - 1)/t
                    bb++;
                    minz = max(ge(bb - x, t), ge(bb, t + 1));
                    maxz = min(le(bb - 1, t), le(bb + y, t + 1));
                    if (maxz >= minz) {
                        ans = max(ans, maxz);
                    }
                }
            }
        }
    }
    cout << ans << endl;

#ifdef LOCAL
    cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
    return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

    if (K < Q) {
        cout << "-1\n";
        return;
    }

    ll ans = -1;

    if (K <= 2*Q) {
        cout << min(N, K-Q + 1 + (N-Q)) << endl;
        return;
    }

    for (ll rev = 1; rev <= 1000000; ++rev) {
        ll take = (K-Q+N + N-Q+1)/(rev+1);
        if (take < N) continue;
        if (take > 2 * N) continue;
        ll s = take - N;
        ll left = (K - Q) - rev * take;
        if (left < 0) continue;
        if (left > Q) continue;
        if (left > s) continue;
        if (min(Q, left + 1) + (N - Q) < s) continue;
        ans = max(ans, s);

    }

    for (ll take = 1; take <= 1000000; ++take) {
        if (take < N) continue;
        if (take > 2 * N) continue;
        ll s = take - N;
        for (ll rev = (K - 2*Q) / take; rev <= (K-Q) / take + 1; ++rev) {
            if (rev <= 0) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0) continue;
            if (left > Q) continue;
            if (left > s) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,l,r,m,s,a,b,ans,M;
void merge(int &L,int &R,int x,int y){
	L=max(L,x);
	R=min(R,y);
}
int chu(int x,int y){
	return x>=0?x/y:x/y-!!(x%y);
}
signed main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&m);
	ans=-1;
	if (l<=r)s=r-l+1;
	else s=n-l+1+r;
	if (m<s){
		puts("-1");
		return 0;
	}
	if (m-s<=s)ans=max(ans,m-s+n-s);
	M=m-s;
	for (int i=n,j;i<=min(M,2*n);i=j+1){
		int k=M/i;j=M/k;
		a=M-k*n,b=-(M-k*n);
		if (!a){ans=max(ans,0ll);continue;}
		int L=(a-s)/k+!!((a-s)%k),R=a/k;
		merge(L,R,-b/(k+1)+!!(-b%(k+1)),chu(n-s-b,k+1));
		if (L<=R)ans=max(ans,R);
	}
	m++;
	if (m-s<=s)ans=max(ans,m-s+n-s);
	M=m-s;
	for (int i=n,j;i<=min(M,2*n);i=j+1){
		int k=M/i;j=M/k;
		a=M-k*n,b=-(M-k*n);
		if (!a)continue;
		int L=(a-s)/k+!!((a-s)%k),R=(a-1)/k;
		merge(L,R,-b/(k+1)+!!(-b%(k+1)),chu(n-s-b,k+1));
		merge(L,R,i-n,j-n);
		if (L<=R)ans=max(ans,R);
	}
	printf("%lld\n",ans);
	return 0;
}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

using namespace std;
#define PB push_back
#define MP make_pair
#define LL long long
#define int LL
#define FOR(i,a,b) for(int i = (a); i <= (b); i++)
#define RE(i,n) FOR(i,1,n)
#define REP(i,n) FOR(i,0,(int)(n)-1)
#define R(i,n) REP(i,n)
#define VI vector<int>
#define PII pair<int,int>
#define LD long double
#define FI first
#define SE second
#define st FI
#define nd SE
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())

#define unordered_map __fast_unordered_map
template<class Key, class Value, class Hash = std::hash<Key>>
using unordered_map = __gnu_pbds::gp_hash_table<Key, Value, Hash>;

template<class C> void mini(C &a4, C b4) { a4 = min(a4, b4); }
template<class C> void maxi(C &a4, C b4) { a4 = max(a4, b4); }

template<class TH> void _dbg(const char *sdbg, TH h){ cerr<<sdbg<<'='<<h<<endl; }
template<class TH, class... TA> void _dbg(const char *sdbg, TH h, TA... a) {
  while(*sdbg!=',')cerr<<*sdbg++;
  cerr<<'='<<h<<','; _dbg(sdbg+1, a...);
}

template<class T> ostream &operator<<(ostream& os, vector<T> V) {
  os << "["; for (auto vv : V) os << vv << ","; return os << "]";
}
template<class L, class R> ostream &operator<<(ostream &os, pair<L,R> P) {
  return os << "(" << P.st << "," << P.nd << ")";
}

#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#else
#define debug(...) (__VA_ARGS__)
#define cerr if(0)cout
#endif

LL N, K, L, R;
LL g1, d1, g2, d2;
LL answer = -1;

int CheckTotalG(LL total_g) {
  if (total_g > N) { return 1; }
  if (total_g < 0) { return -1; }
  const LL div = N + total_g;
  LL m = K % div;
  if (m == 0) { m = div; }
  const LL min_left = max<LL>(0, total_g - d2);
  debug(N, total_g, min_left, m);
  if (m < d1 + max<LL>(0, min_left - 1)) { return 1; }
  if (m > d1 + min<LL>(d1, total_g)) { return -1; }
  debug("ok");
  maxi(answer, total_g);
  return 0;
}

int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout << fixed << setprecision(11);
  cerr << fixed << setprecision(6);

  cin >> N >> L >> R >> K;

  R = (R - L + N) % N;
  L = 0;
  debug(N, K, L, R);

  d1 = R + 1;
  d2 = N - d1;
  debug(d1, d2);
  // max_g = N;

  // const LL max_iter_g = max_g;
  const LL max_iter_g = min(N, (int)(sqrt(K) + 3));

  for (LL tot_g = 0; tot_g <= max_iter_g; ++tot_g)
    CheckTotalG(tot_g);

  for (LL alpha = 0; alpha <= max_iter_g; ++alpha) {
    if (K - alpha * N < 0) { break; }
    LL max_g = alpha ? (K - alpha * N) / alpha : N;
    LL min_g = (K - (alpha + 1) * N + alpha) / (alpha + 1);
    maxi<LL>(min_g, 0);
    mini<LL>(max_g, N);
    if (max_g < min_g) { continue; }

    debug(alpha, min_g, max_g);
    ++max_g;

    while (max_g - min_g > 1) {
      const LL mid_g = (max_g + min_g) / 2;
      if (CheckTotalG(mid_g) == 1)
        max_g = mid_g;
      else
        min_g = mid_g;
    }

    CheckTotalG(max_g);
    CheckTotalG(max_g - 1);
    CheckTotalG(max_g - 2);

  }

  cout << answer << "\n";
}

#include <bits/stdc++.h>
#define LL long long
using namespace std;
LL n,x,k,lb,ub,l,r,ans=-1;
int main() {
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	x=(r>=l?r-l+1:r+n-l+1)%n;
	for(LL i=k,j,r;i;i=j){
		j=k/(k/i+1);r=k/i;
		ub=min(2*n,i);
		lb=max(n,j+1);
		ub=min(ub,min((2*n+k-2*x+1)/(r+1),(k-x)/r));
		lb=max(lb,(k-2*x+r-1)/r);
		if(ub>=lb)ans=max(ans,ub);
	}
	if(x<=k&&k<=x*2)ans=max(ans,n+min(k-x,x-1)+n-x+1);
	if(!x&&k==n)ans=max(ans,n+1);
	printf("%lld\n",~ans?ans-n:ans);
}

#include <bits/stdc++.h>
using namespace std;

const int O = 2e4;

long long floor_div(long long a, long long b) {
  return a / b - ((a ^ b) < 0 && a % b != 0);
}

tuple<long long, long long, long long> gcd(long long a, long long b) {
  if (b == 0)
    return {a, 1, 0};
  auto [g, x, y] = gcd(b, a % b);
  return {g, y, x - y * (a / b)};
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  long long n, l, r, k;
  cin >> n >> l >> r >> k;

  l = r - l + 1;
  if (l <= 0) {
    l += n;
  }
  r = n - l;

  long long ans = -1;
  if (n <= O) {
    for (long long i = 0; i <= l; ++i) {
      for (long long j = 0; j <= r; ++j) {
        long long res = (k - l - i) % (i + j + n);
        if (res > 0) {
          res -= i + j + n;
        }
        if (res == 0 || (i > 0 && res == -1)) {
          ans = max(ans, i + j);
        }
      }
    }
  } else {
    for (long long i = 0; i * n <= k; ++i) {
      auto [g, x, y] = gcd(i + 1, i);
      long long c = k - n * i - l;

      for (int phase = 0; phase < 2; ++phase, ++c) {
        if (c < 0)
          continue;

        long long xx = x * c;
        long long yy = y * c;

        if (i == 0) {
          if (xx >= phase && xx <= l) {
            ans = max(ans, xx + r);
          }
        } else {
          long long max_k = min(floor_div(xx - phase, i), floor_div(r - yy, i + 1));
          if (xx - max_k * i <= l && yy + max_k * (i + 1) >= 0) {
            ans = max(ans, xx + yy + max_k);
          }
        }
      }
    }
  }

  cout << ans << "\n";
}

#include<bits/stdc++.h>
using namespace std;

typedef long long int64;

namespace Template{
	const int L = (1 << 21) | 1;
	char ibuf[L], obuf[20], *iS, *iT, *oT = obuf;

	inline char gc(){
		if(iS == iT){
			iT = (iS = ibuf) + fread(ibuf, 1, L, stdin);
			if(iS == iT)
				return EOF;
		}
		return *iS++;
	}

	#ifndef ONLINE_JUDGE
		#define gc getchar
	#endif

	template<class I>
	void gi(I &ret){
		static char ch;
		while(ch = gc(), !isdigit(ch)) ;
		ret = ch - '0';
		while(ch = gc(), isdigit(ch))
			ret = ret * 10 + ch - '0';
	}

	template<class I>
	void print(I ret){
		if(ret < 0)
			putchar('-'), ret = -ret;
		do
			*oT++ = ret % 10 + '0', ret /= 10;
		while(ret);
		while(oT != obuf)
			putchar(*(--oT));
	}

    template<class I> void scan(I &t) { gi(t); }
    template<class I> void debug(I t) { cerr << t << endl; }
    template<class I, class ...Args> void scan(I &x, Args &...rest) {  gi(x); scan(rest...); }
    template<class I, class ...Args> void debug(I x, Args ...rest) { cerr << x << " "; debug(rest...); }

    template<class I> I min(I x){ return x; }
    template<class I, class ...Args> I min(I x, Args ...rest) { return std::min(x, min(rest...)); }
    template<class I> I max(I x){ return x; }
    template<class I, class ...Args> I max(I x, Args ...rest) { return std::max(x, max(rest...)); }
    template<class I> I sum(I x){ return x; }
    template<class I, class ...Args> I sum(I x, Args ...rest) { return x + sum(rest...); }

	// \lceil \frac{x}{y} \rceil (x \geq 0, y > 0)
	template<class I> inline I pge(I x, I y){ return (x + y - 1) / y; }
	// \lfloor \frac{x}{y} \rfloor (x \geq 0, y > 0)
	template<class I> inline I ple(I x, I y){ return x / y; }
	// \lceil \frac{x}{y} \rceil (y > 0)
	template<class I> inline I ge(I x, I y){ return (x > 0) ? pge(x, y) : -ple(-x, y); }
	// \lfloor \frac{x}{y} \rfloor (y > 0)
	template<class I> inline I le(I x, I y){ return (x > 0) ? ple(x, y) : -pge(-x, y); }
}
using Template::scan;
using Template::print;
using Template::debug;
using Template::min;
using Template::max;
using Template::ge;
using Template::le;

int64 Ans(-1);
int64 n, l, r, k, len;

void check(int64 w){
	if(w < n || w > 2 * n)
		return;
	Ans = max(Ans, w - n);
}

void method1(){
	//len == n
	for(int i = 1; 1ll * i * i <= k; i++){
		if(k % i != 0)
			continue;
		check(static_cast<int64>(i)), check(k / i);
	}
	++k;
	for(int i = 1; 1ll * i * i <= k; i++){
		if(k % i != 0)
			continue;
		check(static_cast<int64>(i)), check(k / i);
	}
}

void method2(){
	for(int rest, i = 0; i <= n; i++){
		rest = k % (i + n);
		if(rest < len || rest > 2 * len)
			goto fail1;
		rest -= len;
		if(i - rest > n - len || i < rest)
			goto fail1;
		Ans = max(Ans, static_cast<int64>(i));

		fail1:
			;

		rest = (k + 1) % (i + n);
		if(rest <= len || rest > 2 * len)
			goto fail2;
		rest -= len;
		if(i - rest > n - len || i < rest)
			goto fail2;
		Ans = max(Ans, static_cast<int64>(i));

		fail2:
			;
	}
}

void method3(){
	//check round == 0
	if(len <= k && k <= 2 * len)
		Ans = (k == 2 * len) ? n: (k - len + 1) + (n - len);
	int64 w, maxz, minz;
	for(int i = 1; i <= static_cast<int>(k / n); i++){
		cerr << i << endl;
		w = k - n * i - len;
		minz = max(ge(w - len, static_cast<int64>(i)), ge(w, static_cast<int64>(i + 1)));
		maxz = min(le(w, static_cast<int64>(i)), le(n - len + w, static_cast<int64>(i + 1)));
		if(maxz >= minz)
			Ans = max(Ans, maxz);

		++w;
		minz = max(ge(w - len, static_cast<int64>(i)), ge(w, static_cast<int64>(i + 1)));
		maxz = min(le(w - 1, static_cast<int64>(i)), le(n - len + w, static_cast<int64>(i + 1)));
		if(maxz >= minz)
			Ans = max(Ans, maxz);
	}
}

int main(){
	scan(n, l, r, k);
	len = r - l + 1, len = (len <= 0) ? (len + n) : len;
//	debug(len);
//	debug(k, len);
	if(len == n)
		method1();
	else if(n <= 1000000ll)
		method2();
	else method3();

	print(Ans);

	return 0;
}

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main(){
    ll n,r0,r,k;
    scanf("%lld%lld%lld%lld",&n,&r0,&r,&k);
    r=(r-r0+n)%n+1;
    ll ans=-1;
    if(n<10000){
        for(ll slack=0;slack<2;slack++){
            for(ll a=slack;a<=r;a++){
                ll k0=k+slack-a-r;
                if(k0<0)break;
                else if(k0==0)ans=max(ans,a+n-r);
                else {
                    for(ll i=n+a;i<=n*2-r+a;i++)
                        if(k0%i==0)ans=max(ans,i-n);
                }
            }
        }
    }
    else {
        for(ll slack=0;slack<2;slack++){
            ll k0=k+slack;
            for(ll l=0;n*l+r<=k0;l++){
                ll b=((n-r)+(k0-n*l-r))/(l+1)*(l+1)-(k0-n*l-r);
                if(b<0)continue;
                ll a=(k0-(n+b)*l-r)/(l+1);
                if(a<slack||a>r)continue;
                ans=max(ans,a+b);
            }
        }
    }
    printf("%lld\n",ans);
}

#include <bits/stdc++.h>
#define ll long long
#define mst(a,x) memset(a,x,sizeof(a))
#define For(i, t) for(int i = 0; i < t; i++)
#define Debug(x) cerr << #x << " = "  << x << endl;
using namespace std;

ll x, y, n, l, r, k, ans;

void check(ll t) {
    ll L = max(max(k / (t + 1) + 1, n), (k - 2 * x + t - 1) / t);
    ll R = min(min((k - x) / t, 2*n), (2*n - 2*x + k + 1) / (t + 1));
    if(L <= R) ans = max(ans, R - n);
}

int main() {
    cin >> n >> l >> r >> k;
    x = (r - l + 1 + n) % n;
    // t == 0
    ans = -1;
    if(k <= 2 * x && k >= x) ans = min(x, k - x + 1) + n - x;
    if(x == 0 && k <= 2 * n && k >= n) ans = min(n, k - n + 1);

    for(ll i = 1; i <= k; i = k / (k / i) + 1)
        check(k / i);

    cout << ans << "\n";

	return 0;
}

#pragma GCC optimize("O3")
#ifdef ONLINE_JUDGE
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#endif
#pragma GCC optimize("unroll-loops")
#pragma comment(linker, "/stack:200000000")
#include <bits/stdc++.h>
#include <type_traits>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
template<typename Key=int,typename Mapped=__gnu_pbds::null_type,typename Cmp_Fn=std::less<Key>,typename Tag=__gnu_pbds::rb_tree_tag,template<typename Const_Node_Iterator,typename Node_Iterator,typename Cmp_Fn_,typename Allocator_>class Node_Update=__gnu_pbds::tree_order_statistics_node_update,typename Allocator=std::allocator<char>>class ordered_set_t:__gnu_pbds::tree<Key,Mapped,Cmp_Fn,Tag,Node_Update,Allocator>{};const int GRANDOM=std::chrono::high_resolution_clock::now().time_since_epoch().count();struct ghash{int operator()(int x){return std::hash<int>{}(x^GRANDOM);}};template<typename KeyType>class hash_table_t:__gnu_pbds::gp_hash_table<KeyType,int,ghash>{};namespace vh{template<class T>void _R(T&x){std::cin>>x;}inline void _R(int&x){scanf("%d",&x);}inline void _R(int64_t&x){scanf("%" SCNd64,&x);}inline void _R(double&x){scanf("%lf",&x);}inline void _R(char&x){scanf(" %c",&x);}inline void _R(char*x){scanf("%s",x);}inline void R(){}template<class T,class... U>inline void R(T&head,U&... tail){_R(head);R(tail...);}template<class T>void _W(const T&x){cout<<x;}inline void _W(const int&x){printf("%d",x);}inline void _W(const int64_t&x){printf("%" PRId64,x);}inline void _W(const double&x){printf("%.16f",x);}inline void _W(const char&x){putchar(x);}inline void _W(const char*x){printf("%s",x);}template<class T>inline void _W(const vector<T>&x){for(auto i=x.begin();i!=x.end();_W(*i++))if(i!=x.cbegin())putchar(' ');}inline void W(){}template<class T,class... U>inline void W(const T&head,const U&... tail){_W(head);if(sizeof...(tail))putchar(' '),W(tail...);}template<class T,class... U>inline void WL(const T&head,const U&... tail){_W(head);putchar(sizeof...(tail)? ' ':'\n');W(tail...);}};
#define prec setprecision
namespace vh{typedef long long ll;typedef unsigned long long llu;template<typename T>T gcd(T m,T n){while(n){T t=m%n;m=n;n=t;};return m;}template<typename T>T exgcd(T a,T b,T&sa,T&ta){T q,r,sb=0,tb=1,sc,tc;sa=1,ta=0;if(b)do q=a/b,r=a-q*b,a=b,b=r,sc=sa-q*sb,sa=sb,sb=sc,tc=ta-q*tb,ta=tb,tb=tc;while(b);return a;}template<typename T>T mul_inv(T a,T b){T t1=a,t2=b,t3;T v1=1,v2=0,v3;T x;while(t2!=1)x=t1/t2,t3=t1-x*t2,v3=v1-x*v2,t1=t2,t2=t3,v1=v2,v2=v3;return(v2+b)%b;}template<typename T>T powmod(T a,T b,T MOD){if(b<0)return 0;T rv=1;while(b)(b%2)&&(rv=(rv*a)%MOD),a=a*a%MOD,b/=2;return rv;}template<typename T>inline T isqrt(T k){T r=sqrt(k)+1;while(r*r>k)r--;return r;}template<typename T>inline T icbrt(T k){T r=cbrt(k)+1;while(r*r*r>k)r--;return r;}template<typename T>bool mul_overflow(T&r,T a,T b){return __builtin_mul_overflow(a,b,&r);}template<ll n>struct BitSize{enum{Size=BitSize<n/2>::Size+1};};template<>struct BitSize<0>{enum{Size=1};};template<>struct BitSize<1>{enum{Size=1};};
#define BITSIZE(n) (BitSize<n>::Size)
#define BITMAX(n) (BitSize<n>::Size - 1)
#define DEBUG !defined(ONLINE_JUDGE)
#define SZ(x) ((int)(x).size())
#define ALL(x) begin(x), end(x)
template<typename TH>void _dbg(const char*sdbg,TH h){cerr<<sdbg<<"="<<h<<"\n";}template<typename TH,typename... TA>void _dbg(const char*sdbg,TH h,TA... t){while(*sdbg!=',')cerr<<*sdbg++;cerr<<"="<<h<<",";_dbg(sdbg+1,t...);}
#ifdef DEBUG
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; for(auto itt: x) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
}namespace vh{template<typename T>int min_rotation(vector<T>s){int a=0,N=s.size();for(int b=0;b<N;b++)for(int i=0;i<N;i++){if(a+i==b||s[(a+i)%N]<s[(b+i)%N]){b+=max(0,i-1);break;}if(s[(a+i)%N]>s[(b+i)%N]){a=b;break;}}return a;}}namespace vh{};
namespace vh{
  int brute(int n,int l,int r,int k,bool with_last){
    int p=l<=r ?(r-l+1):(n+2-(l-r+1));
    int best=-1;
    if(p<=k&&k<=p*2){
      if(!with_last){
        best=max(best,min(p,k-p+1)+(n-p));
      }else{
        best=max(best,(k-p)+(n-p));
      }
    }
    for(int s=1;s<=k;s++){
      int a,b;
      if(k%s==0)a=s,b=0;
      else a=k%s,b=s-a;
      if(
          (with_last ?(p<a):(p<=a))&&a<=p*2
          &&(n-p)<=b&&b<=(n-p)*2
      ){
        best=max(best,s-n);
      }
    }
    return best;
  }
  inline ll div_ceil(ll a,ll b){
    return(a+b-1)/b;
  }
  inline ll div_floor(ll a,ll b){
    return a/b;
  }
  ll solve(ll n,ll l,ll r,ll k,bool with_last){
    ll p=l<=r ?(r-l+1):(n+2-(l-r+1));
    ll best=-1;
    if(p<=k&&k<=p*2){
      if(!with_last)best=max(best,min(p,k-p+1)+(n-p));
      else best=max(best,min(p,k+1-p)+(n-p));
    }
    ll q=n-p;
    if(with_last)k++;
    clock_t s1=clock();
    for(ll x=1;x<=k/x;x++){
      ll amin=n;
      amin=max(amin,div_ceil(k,x+1));
      amin=max(amin,div_ceil(k-(p+with_last)*2,x));
      amin=max(amin,div_ceil(q+k,x+1));
      ll amax=n*2;
      amax=min(amax,div_ceil(k,x));
      if(with_last)amax=min(amax,div_ceil(k-p,x)-1);
      else amax=min(amax,div_floor(k-p,x));
      amax=min(amax,div_floor(k+q*2,x+1));
      if(amin<=amax){
        best=max(best,amax-n);
      }
    }
    for(ll a=n,am=n*2;a<=am&&a<=k/a;a++){
      ll b=k%a;
      if(b==0)b=a;
      if(
        (with_last ?(p<b):(p<=b))&&b<=p*2&&q<=a-b&&a-b<=q*2
      ){
        best=max(best,a-n);
      }
    }
    return best;
  }
  int main(){
    srand(GRANDOM);
    ll n,l,r,k;
    cin>>n>>l>>r>>k;
    cout<<max(
      solve(n,l,r,k,false),
      solve(n,l,r,k,true)
    )<<endl;
    return 0;
  }
};
int main(int argc,char*argv[]){
  std::cin.sync_with_stdio(false);std::cin.tie(nullptr);
  return vh::main();
}

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const LL P=500000;
LL n,m,l,r,k;

bool check(LL t){
	LL tot=n+t,rest=m%tot;
	if (!rest) rest=tot;
	LL mn=max(0LL,t-(n-k)),mx=min(k,t);
	if (k+mx>=rest&&k+mn-(mn>0)<=rest) return 1;
	return 0;
}

LL calc(LL num){
	LL l=0,r=n;
	if (num) r=min(r,m/num-n);
	if (m-2*k>0){
		if (!num) return -1;
		l=max(l,(m-2*k+num-1)/num-n);
	}
	if (m-k-n*num>=0){
		l=max(l,(m-k-n*num+num)/(num+1));
	}
	if (m-k>=0){
		if (num) r=min(r,(m-k)/num-n);
	}
	else return -1;
	if (m-n*(num-1)-2*k+1>=0){
		r=min(r,(m-n*(num-1)-2*k+1)/(num+1));
	}
	else return -1;
	if (l>r) return -1;
	return r;
}

int main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&m);
	k=r<l?r-l+1+n:r-l+1;
	if (n<=P){
		for (LL i=n;~i;--i){
			if (check(i)){
				printf("%lld\n",i);
				return 0;
			}
		}
		puts("-1");
	}
	else{
		LL ans=-1;
		for (LL i=m/n;~i;--i){
			ans=max(ans,calc(i));
		}
		printf("%lld\n",ans);
	}

	return 0;
}

//~ while (clock()<=69*CLOCKS_PER_SEC)
//~ #pragma comment(linker, "/stack:200000000")
//~ #pragma GCC optimize("O3")
//~ #pragma GCC optimize("Ofast")
//~ #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//~ #pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define pb push_back
#define SZ(x) ((int)(x).size())
#define ALL(x) x.begin(),x.end()
#define all(x) x.begin(),x.end()
#define fi first
#define se second
#define _upgrade ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define erase_duplicates(x) sort(all(x)); (x).resize(distance((x).begin(), unique(all(x))));

using namespace std;
using namespace __gnu_pbds;
template<typename T>
using ordered_set = tree<
T,
null_type,
less<T>,
rb_tree_tag,
tree_order_statistics_node_update>;

//X.find_by_order(k); - zwraca iterator na k-ty element (numeracja od zerowego)
//X.order_of_key(k); - zwraca liczbę elementów ostro mniejszych niż k

typedef long long LL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
typedef vector<PII> VPII;
typedef vector<PLL> VPLL;
typedef vector<LL> VLL;
typedef vector<int> VI;
typedef vector<string> VS;
typedef vector<char> VC;
typedef long double LD;
typedef pair<LD,LD> PLD;
typedef vector<LD> VLD;
typedef vector<PLD> VPLD;

template<class TH> void _dbg(const char *sdbg, TH h){ cerr<<sdbg<<" = "<<h<<endl; }
template<class TH, class... TA> void _dbg(const char *sdbg, TH h, TA... a) {
  while(*sdbg!=',')cerr<<*sdbg++;
  cerr<<" = "<<h<<", "; _dbg(sdbg+1, a...);
}

#ifdef LOCAL
#define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#else
#define dbg(...)
#define cerr if(0)cout
#endif

const int maxn = (1e6)+7;
const int maxk = 20;
const int inf = (1e9)+7;
const LL LLinf = ((LL)1e18)+7LL;
const LD eps = 1e-9;
const LL mod = 1e9+7;

// ***************************** CODE ***************************** //

int main()
{
	_upgrade
  LL n, k, x, y;
  cin>>n>>x>>y>>k;
  y -= x - 1;
  while(y <= 0)
    y += n;
  x = n - y;
  // dbg(x, y, n);
  if(n < 1e4)
  {
    LL res = -1LL;
    for(LL a = 0;a <= x;a++)
      for(LL b = 0;b <= y;b++)
        if((b > 0 && ((k - b - y + 1) % (a + x + b + y) == 0)) || ((k - b - y) % (a + x + b + y) == 0))
          res = max(res, a + b);
    cout<<res;
  }
  else
  {
    dbg("xd");
    LL m = k / n;
    LL res = -1, L1, L2, R1, R2;
		if(y <= k && k <= y * 2)
      res = max(res, k == y * 2 ? n : (n - y) + (k - y + 1));
		for(int i = 1; i <= m ;i++)
    {
			L1 = (k - y * 2 + i - 1) / i - n;
			R1 = (k - y) / i - n;
			L2 = (k + n - y + i) / (i + 1) - n;
			R2 = (k + (n - y) * 2 + 1) / (i + 1) - n;
			if (max(L1, L2) <= min(R1, R2))
				res = max(res, min(R1, R2));
		}
    cout<<res;
  }
	return 0;
}

#include <bits/stdc++.h>
// #pragma GCC optimize ("O3")
// #pragma GCC target ("sse4")
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;

#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for (int i=(a); i<(b); ++i)
#define FORD(i,a,b) for (int i=(a)-1; i>=(b); --i)

#define pb push_back
#define mp make_pair
#define st first
#define nd second

const int MOD = 1000000007;

LL check(LL N, LL K, LL incomplete, LL o) {
  if (o == 0) {
    if (K < incomplete) return -1;
    if (K > 2*incomplete) return -1;
    return K - incomplete + (K < 2*incomplete) + (N - incomplete);
  }

  if (K / o < N) return -1;

  K -= o*N + incomplete;
  if (K < 0) return -1;

  LL S = K % o;
  if (S > incomplete) return -1;
  if (K / (o+1) < S) return -1;
  K -= (o+1) * S;
  incomplete -= S;
  N -= S;

  if (K == 0) return S;
  if (N == 0) return -1;

  LL res = -1;
  // 1. ostatni wziął
  {
    LL max_in_other = o * (N - incomplete);
    LL min_in_incomplete = max(0LL, (K - max_in_other + o) / (o+1));
    if (min_in_incomplete % o) {
      min_in_incomplete = (min_in_incomplete - min_in_incomplete % o) + o;
    }
    bool ok = true;
    if (min_in_incomplete > incomplete) ok = false;
    LL in_other = (K - min_in_incomplete * (o+1)) / o;
    if (in_other > N - incomplete) ok = false;
    if (ok && o * in_other + (o+1) * min_in_incomplete == K) res = max(res, in_other + min_in_incomplete + S);
  }

  // 2. ostatni nie wziął
  {
    if (incomplete == 0) return res;
    --incomplete;

    LL max_in_other = o * (N - incomplete);
    LL min_in_incomplete = max(0LL, (K - max_in_other + o) / (o+1));
    if (min_in_incomplete % o) {
      min_in_incomplete = (min_in_incomplete - min_in_incomplete % o) + o;
    }
    bool ok = true;
    if (min_in_incomplete > incomplete) ok = false;
    LL in_other = (K - min_in_incomplete * (o+1)) / o;
    if (in_other > N - incomplete) ok = false;
    if (ok && o * in_other + (o+1) * min_in_incomplete == K) res = max(res, in_other + min_in_incomplete + S);
  }

  return res;
}

LL N, L, R, K, incomplete;

int main() {
  ios_base::sync_with_stdio(0);

  cin >> N >> L >> R >> K;

  incomplete = (R-L+1 + N) % N;
  if (!incomplete) incomplete = N;

  LL result = -1;
  REP(o,1e6) result = max(result, check(N, K, incomplete, o));
  REP(r,min(N+1,(LL)1e6)) {
    LL o = K / (N + r);
    result = max(result, check(N, K, incomplete, o));
    result = max(result, check(N, K, incomplete, max(0LL, o - 1)));

  }
  cout << result << endl;
}

#include <bits/stdc++.h>
using namespace std;

const long long N = 5e5;

int main(){
	long long n, l, r, k, rem, ans, cir, left, ll, rr, mid, maxx;
	cin >> n >> l >> r >> k;
	if (r >= l) rem = r - l + 1;
	else rem = r - l + 1 + n;
	ans = -1;
	for (long long i = min(n, N); i >= 0; i--){
		left = k % (n + i);
		if (left == 0) left = n + i;
		maxx = max(0LL, i - n + rem);
		if (left >= rem + max(0LL, maxx - 1) && left <= rem + min(rem, i)){
			ans = i;
			break;
		}
	}
	for (long long i = 0; i <= min(n, N); i++){
		ll = 0;
		rr = n + 1;
		while (rr - ll > 1){
			mid = (ll + rr) >> 1;
			maxx = max(0LL, mid - n + rem);
			if ((n + mid) * i + rem + max(0LL, maxx - 1) <= k) ll = mid;
			else rr = mid;
		}
		left = k % (n + ll);
		if (left == 0) left = n + ll;
		maxx = max(0LL, ll - n + rem);
		if (left >= rem + max(0LL, maxx - 1) && left <= rem + min(rem, ll)) ans = max(ans, ll);
	}
	cout << ans << '\n';
	return 0;
}

//By Tushar Gautam
#pragma GCC optimize ("-O2")
#include <bits/stdc++.h>
using namespace std;
#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define memreset(a) memset(a,0,sizeof(a))
#define testcase(t) int t;cin>>t;while(t--)
#define forstl(i,v) for(auto &i: v)
#define forn(i,e) for(int i = 0; i < e; i++)
#define forsn(i,s,e) for(int i = s; i < e; i++)
#define rforn(i,s) for(int i = s; i >= 0; i--)
#define rforsn(i,s,e) for(int i = s; i >= e; i--)
#define leadzero(a) __builtin_clz(a) // count leading zeroes
#define trailzero(a) __builtin_ctz(a) // count trailing zeroes
#define bitcount(a) __builtin_popcount(a) // count set bits (add ll)
#define ln "\n"
#define dbg(x) cout<<#x<<" = "<<x<<ln
#define dbg2(x,y) cout<<#x<<" = "<<x<<" & "<<#y<<" = "<<y<<ln;
#define dbgstl32(v) cout<<#v<<" = \n"; { int c=0; forstl(it,v) \
cout<<"    Term "<< ++c <<" = "<<it<<ln;} cout<<ln
#define dbgstlp32(v) cout<<#v<<" = \n"; { int c=0; forstl(it,v) \
cout<<"    Term "<< ++c <<" = "<<it.fi<<" , "<<it.se<<ln;} cout<<ln
#define dbgarr(v,s,e) cout<<#v<<" = "; forsn(i,s,e) cout<<v[i]<<", "; cout<<ln
#define inp freopen("input.txt", "r", stdin)
#define outp freopen("output.txt", "w", stdout)
typedef long long int  ll;
typedef long double  ld;
typedef pair<ll,ll> p64;
typedef pair<int,int> p32;
typedef vector<ll> v64;
typedef vector<int> v32;
typedef vector<v32> vv32;
typedef vector<v64> vv64;
typedef vector<p32> vp32;
typedef vector<vp32> vvp32;
typedef map<int,int> m32;
const int LIM = 1e5+5, MOD = 1e9+7;
ll t,n,m,k,l,r,x,y;
inline ll check1(ll &a,ll &b,ll &c,int &i){
	// i*(x+y) = t-x
	//dbg(a);dbg(b);dbg(c);dbg(i);
	if(!(a+i*c>=0 && a+i*c<=m)) return -1;
	if(!(b-a-(i+1)*c>=0 && b-a-(i+1)*c<=n-m)) return -1;
	return b-c;
}
inline ll check2(ll &a,ll &b,ll &c,int &i){
	// i*(x+y) = t-x
	//dbg(a);dbg(b);dbg(c);dbg(i);
	if(!(a+i*c>=1 && a+i*c<=m)) return -1;
	if(!(b-a-(i+1)*c>=0 && b-a-(i+1)*c<=n-m)) return -1;
	return b-c;
}
ll solve(){
	ll ans=-1;
	if(k<0) return ans;
	// 0 <= x <= m , 0 <= y <= n-m , r>=0
	// r*(x+y+n)+x = k || r*(x+y+n)+x = k+1 ,x>=1
	if(n<5e3){
		forn(i,n-m+1){
			forn(j,m+1){
				// k+i+n = (r+1)*(i+j+n)
				if((k+i+n)%(i+j+n)==0 && k>=j){
					ans=max(ans,(ll)i+j);
					if(ans==6007) {dbg(i);dbg(j);}
				}
				// k+1+i+n = (r+1)*(i+j+n)
				if(j>0 && (k+1+i+n)%(i+j+n)==0 && k+1>=j){
					ans=max(ans,(ll)i+j);
					if(ans==6007) {dbg(i);dbg(j);}
				}
			}
		}
	}else{
		//dbg(k);dbg(n);dbg(m);dbg(n-m);
		forsn(i,max(k/(2*n)-1,0LL),k/n+2){
			// i*(x+y+n)+x = k => (i+1)*x + i*y = k-i*n = t => i*(x+y) = t-x or t+y=(i+1)*(x+y)
			t=k-i*n;
			if(t>=0){
				// Check Line's Extreme points x=0,x=m,y=0,y=n-m
				if(i>0){
					ll alpha = t%i, beta = t/i;
					ll gammaMn= max(ceil(-alpha/(double)i),ceil((beta-alpha+m-n)/(double)(i+1)));
					ll gammaMx= min(floor((m-alpha)/(double)i),floor((beta-alpha)/(double)(i+1)));
					if(gammaMx<gammaMn) continue;
					ans=max(ans,check1(alpha,beta,gammaMn,i));
					ans=max(ans,check1(alpha,beta,gammaMx,i));
					gammaMx++;gammaMn--;
					ans=max(ans,check1(alpha,beta,gammaMx,i));
					ans=max(ans,check1(alpha,beta,gammaMn,i));
				}else if(i==0 && t<=m){
					ans=max(ans,t+n-m);
				}
			}
			t++;
			if(t>=0 && m>0){
				// Check Line's Extreme points x=1,x=m,y=0,y=n-m
				if(i>0){
					ll alpha = t%i, beta = t/i;
					ll gammaMn= max(ceil(-alpha/(double)i),ceil((beta-alpha+m-n)/(double)(i+1)));
					ll gammaMx= min(floor((m-alpha)/(double)i),floor((beta-alpha)/(double)(i+1)));
					if(gammaMx<gammaMn) continue;
					ans=max(ans,check2(alpha,beta,gammaMn,i));
					ans=max(ans,check2(alpha,beta,gammaMx,i));
					gammaMx++;gammaMn--;
					ans=max(ans,check2(alpha,beta,gammaMx,i));
					ans=max(ans,check2(alpha,beta,gammaMn,i));
				}else if(i==0 && t>0 && t<=m){
					ans=max(ans,t+n-m);
				}
			}
		}
	}
	return ans;
}
int main(){
    fastio;
    cin>>n>>l>>r>>k;
    r-=l;
    if(r<0) r+=n;
    m=r+1;
    k-=m;
    ll ans=-1;
    ans=max(ans,solve());
    cout<< ans <<ln;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;

long long n, l, r, k;

//[n-M -> 2*(n-M)]*C + [M -> 2M]*(C+1) == k

long long checkC(long long n, long long M, long long k, long long C, bool mustR = false) {
	//printf("check %lld %lld %lld %lld\n",n,M,k,C);
	k -= n*C;
	k -= M;
	if (k < 0) return -1;

	if (C == 0) {
		if (k == 0 && mustR) return -1;
		if (k > M) return -1;
		return k + n-M;
	}

	long long sweetR = k % C;
	if (sweetR > M) return -1;
	k -= sweetR * (C+1);
	if (k < 0) return -1;

	long long sweetL = (C+1) - (k % (C+1));
	if (sweetL == C+1) sweetL = 0;
	if (sweetL > n-M) return -1;
	k -= sweetL * C;
	if (k < 0) return -1;

	if (sweetR == 0 && mustR) {
	 	sweetR += C;
	 	k -= sweetR * (C+1);
	 	if (k < 0) return -1;
	}

	long long otL = (C+1) * min( (n-M-sweetL) / (C+1), k / C/(C+1)) ;
	k -= otL * C;

	long long otR = C * min( (M - sweetR) / C, k /C/(C+1)) ;
	k -= otR * (C+1);

	if (k != 0) return -1;
	return sweetL + otL + otR + sweetR;
}

void goC(long long n, long long M, long long k) {
	long long ans = -1;

	for (int C = 0; C <= k/n; C++) {
		ans = max(ans, checkC(n,M,k,C));
	}

	for (int C = 0; C <= k/n; C++) {
		ans = max(ans, checkC(n,M,k+1,C,true));
	}

	printf("%lld\n", ans);
}

long long checkN(long long L, long long R, long long k, long long swL, long long swR) {
	// [L+swL] * C + [R+swR] * (C+1) == k
	k -= R+swR;
	if (k < 0) return -1;

	long long C = k / (L+swL+R+swR);
	if (C * (L+swL+R+swR) == k) return swL+swR;
	return -1;
}

void goN(long long n, long long M, long long k) {
	long long ans = -1;
	for (int swL = 0; swL <= n-M; swL++) {
		for (int swR = 0; swR <= M; swR++) {
			ans = max(ans, checkN(n-M, M, k, swL, swR));
		}
	}

	for (int swL = 0; swL <= n-M; swL++) {
		for (int swR = 1; swR <= M; swR++) {
			ans = max(ans, checkN(n-M, M, k+1, swL, swR));
		}
	}

	printf("%lld\n", ans);
}

int main() {
	scanf("%lld %lld %lld %lld", &n, &l, &r, &k);

	r -= l;
	if (r < 0) r += n;
	r++;

	if (k/n <= 10000000)
	  	goC(n, r, k);
	else
		goN(n, r, k);
}

#include <iostream>
#include <ios>
#include <cstdint>
#include <vector>
#include <string>
#include <random>
#include <utility>
#include <ctime>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <complex>
#include <queue>
#include <cstdio>
#include <iomanip>

using ul = std::uint32_t;
using li = std::int32_t;
using ull = std::uint64_t;
using ll = std::int64_t;
using vul = std::vector<ul>;
using vvul = std::vector<vul>;
using vb = std::vector<bool>;
using vvb = std::vector<vb>;
using vvvb = std::vector<vvb>;
using vull = std::vector<ull>;
using vvull = std::vector<vull>;
using vli = std::vector<li>;
using vll = std::vector<ll>;
using pulul = std::pair<ul, ul>;
using vpulul = std::vector<pulul>;
using lf = double;
using vlf = std::vector<lf>;

ll n, k, l, r;
std::mt19937 rands;

ll up(ll a, ll b)
{
	return a < 0 ? a / b : (a + b - 1) / b;
}

ll low(ll a, ll b)
{
	return a < 0 ? (a - b + 1) / b : a / b;
}

int main()
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::cin >> n >> l >> r >> k;
	r = (r + n - l + 1) % n;
	if (!r) {
		r = n;
	}
	if (n < k / n) {
		for (ll t = n; ~t; --t) {
			ll b = k % (n + t);
			if (!b) {
				b = n + t;
			}
			if (b <= 2 * r && b <= t + r && b >= r && b >= t + 2 * r - n - 1) {
				std::cout << t << std::endl;
				return 0;
			}
		}
		std::cout << "-1" << std::endl;
		return 0;
	} else {
		ll ans = -1;
		for (ll a = 0; a * n < k; ++a) {
			if (!a) {
				if (k <= 2 * r && k >= r) {
					ll s = std::max(k - r, ll(0));
					ll t = std::min(k - 2 * r + n + 1, n);
					if (t >= s) {
						ans = std::max(ans, t);
					}
				}
				continue;
			}
			ll s = std::max(std::max(up(k - a * n - 2 * r, a), up(k - a * n - r, a + 1)), ll(0));
			ll t = std::min(std::min(low(k - a * n - r, a), low(k - a * n + n - 2 * r + 1, a + 1)), n);
			if (t >= s) {
				ans = std::max(ans, t);
			}
		}
		std::cout << ans << std::endl;
	}
	return 0;
}

#include <cstdio>

typedef long long ll;

const ll X = 2e5;

int main() {
    ll n, l, r, k;
    scanf("%lld %lld %lld %lld", &n, &l, &r, &k);
    r = (r - l + n) % n + 1;

    ll ans = -1;
    if (n <= X) {
        for (ll i = n; i >= 0; i--) {
            ll y = (k - 1) % (n + i) + 1 - r;
            if (y < 0 || y > r || y > i || y < i + r - n - 1) {
                continue;
            }
            ll y2 = y + 1;
            if (y2 <= r && y2 <= i) {
                ans = i;
                break;
            }
            if (y >= i + r - n) {
                ans = i;
                break;
            }
        }
    } else {
        for (ll i = 0; i <= k / n; i++) {
            ll p = (k - (i - 1) * n - 2 * r + 1) / (i + 1);
            ll y = k - i * (n + p) - r;
            if (y < 0) {
                if (i == 0) {
                    continue;
                }
                int d = (-y - 1) / i + 1;
                y += i * d;
                p -= d;
            }
            if (p > n) {
                y += i * (p - n);
                p = n;
            }
            if (y > r || y > p || p < 0 || y + 1 < p + r - n) {
                continue;
            }
            ll y2 = y + 1;
            if (y >= p + r - n) {
                if (p > ans) {
                    ans = p;
                }
            }
            if (y2 <= r && y2 <= p) {
                if (p > ans) {
                    ans = p;
                }
            }
        }
    }

    printf("%lld\n", ans);

    return 0;
}

#include <bits/stdc++.h>
#define int long long
int n,l,r,k;
signed main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	int c=(r+n-l+1)%n;
	if (n<1000000){
		int ans=-1;
		for (int i=0;i<=n;i++){
			int t=k%(n+i)-c;
			if (t<0) continue;
			if (t<=i && t<=c && (c-t<=n-i+1)) ans=std::max(ans,i);
		}
		printf("%lld\n",ans);
	}else{
		int ans=-1;
		if (k==n) ans=1;
		if (k==c) ans=n-c;
		if (k-c<=c && k-c>=0) ans=std::min(k-c+1,c)+n-c;
		for (int i=1;i<=k/n;i++){
			int t=k-n*i-c;
			if (t<0) break;
			int ml=std::max((t-c-1)/i+1,(t-1)/(i+1)+1),mr=(t+n+1-c)/(i+1);
			mr=std::min(mr,t/i);
			if (ml<=mr) ans=std::max(ans,mr);
		}
		printf("%lld\n",ans);
	}
}

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<ctime>
#include<utility>
#include<functional>
#include<cmath>
#include<vector>
#include<iostream>
//using namespace std;
using std::min;
using std::max;
using std::swap;
using std::sort;
using std::reverse;
using std::random_shuffle;
using std::lower_bound;
using std::upper_bound;
using std::unique;
using std::vector;
using std::cin;
using std::cout;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef std::pair<int,int> pii;
typedef std::pair<ll,ll> pll;
void open(const char *s){
#ifndef ONLINE_JUDGE
	char str[100];sprintf(str,"%s.in",s);freopen(str,"r",stdin);sprintf(str,"%s.out",s);freopen(str,"w",stdout);
#endif
}
void open2(const char *s){
#ifdef DEBUG
	char str[100];sprintf(str,"%s.in",s);freopen(str,"r",stdin);sprintf(str,"%s.out",s);freopen(str,"w",stdout);
#endif
}
int rd(){int s=0,c,b=0;while(((c=getchar())<'0'||c>'9')&&c!='-');if(c=='-'){c=getchar();b=1;}do{s=s*10+c-'0';}while((c=getchar())>='0'&&c<='9');return b?-s:s;}
void put(int x){if(!x){putchar('0');return;}static int c[20];int t=0;while(x){c[++t]=x%10;x/=10;}while(t)putchar(c[t--]+'0');}
int upmin(int &a,int b){if(b<a){a=b;return 1;}return 0;}
int upmax(int &a,int b){if(b>a){a=b;return 1;}return 0;}
typedef long double ldb;
ll n,k;
ll l,r;
ll ans=-1;
ll len;
void gao(ll i)
{
	ll l=min((k-2*len+2*n+1)/(i+1),(k-len)/i);
	if(((ldb)i*l+len<1e18&&i*l+len<=k)&&((ldb)i*l+2*len+l-2*n-1<1e18&&i*l+2*len+l-2*n-1<=k)&&((ldb)i*l+len+l-n>1e18||i*l+len+l-n>=k)&&((ldb)i*l+2*len>1e18||i*l+2*len>=k))
		ans=max(ans,l-n);
}
int main()
{
	open("d");
	cin>>n>>l>>r>>k;
	len=(r>=l?r-l+1:n-l+1+r);
	if(n<=1000000)
	{
		for(int i=n;i<=2*n;i++)
		{
			ll s=k%i;
			if(s==0)
				s=i;
			s-=len;
			ll mi=max(i-n-(n-len)-1,0ll);
			ll ma=min(len,i-n);
			if(s>=mi&&s<=ma)
				ans=max(ans,i-n);
		}
	}
	else
	{
		//i=0
		if(k>=len&&k<=2*len)
			ans=max(ans,k==2*len?n:n-len+k-len+1);
		for(int i=1;i<=k/n;i++)
			gao(i);
	}
	cout<<ans<<std::endl;
	return 0;
}

// hloya template v25

// ░░░░░░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░░░░░
// ░░░░░░█░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░█░░░░░
// ░░░░░░█░█░▀░░░░░▀░░▀░░░░█░█░░░░░
// ░░░░░░█░█░░░░░░░░▄▀▀▄░▀░█░█▄▀▀▄░
// █▀▀█▄░█░█░░▀░░░░░█░░░▀▄▄█▄▀░░░█░
// ▀▄▄░▀██░█▄░▀░░░▄▄▀░░░░░░░░░░░░▀▄
// ░░▀█▄▄█░█░░░░▄░░█░░░▄█░░░▄░▄█░░█
// ░░░░░▀█░▀▄▀░░░░░█░██░▄░░▄░░▄░███
// ░░░░░▄█▄░░▀▀▀▀▀▀▀▀▄░░▀▀▀▀▀▀▀░▄▀░
// ░░░░█░░▄█▀█▀▀█▀▀▀▀▀▀█▀▀█▀█▀▀█░░░
// ░░░░▀▀▀▀░░▀▀▀░░░░░░░░▀▀▀░░▀▀░░░░

#include <bits/stdc++.h>
using namespace std;

bool dbg = 0;

clock_t start_time = clock();
#define current_time fixed<<setprecision(6)<<(ld)(clock()-start_time)/CLOCKS_PER_SEC

#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(x) (x).begin(), (x).end()

#define ll long long int
#define ld long double
#define pii pair<int,int>
#define umap unordered_map<int, int>

#define files1 freopen("input.txt","r",stdin)
#define files2 freopen("output.txt","w",stdout)
#define files files1;files2
#define fast_io ios_base::sync_with_stdio(0);cin.tie(0)

#define endl '\n'
#define ln(i,n) " \n"[(i) == (n) - 1]

void bad(string mes = "Impossible"){cout << mes;exit(0);}
void bad(int mes){cout << mes;exit(0);}

template<typename T>
string bin(T x, int st = 2){
    string ans = "";
    while (x > 0){
        ans += char('0' + x % st);
        x /= st;
    }
    reverse(ans.begin(), ans.end());
    return ans.empty() ? "0" : ans;
}

template<typename T>
void amax(T& x, T y) {
    x = max(x, y);
}

template<typename T>
void amin(T& x, T y) {
    x = min(x, y);
}

// inline int popcount(int x){
//     int count = 0;
//     __asm__ volatile("POPCNT %1, %0;":"=r"(count):"r"(x):);
//     return count;
// }

template<typename T>
T input(){
    T ans = 0, m = 1;
    char c = ' ';

    while (!((c >= '0' && c <= '9') || c == '-')) {
        c = getchar();
    }

    if (c == '-')
        m = -1, c = getchar();
    while (c >= '0' && c <= '9'){
        ans = ans * 10 + (c - '0'), c = getchar();
    }
    return ans * m;
}

ll gcd (ll a, ll b) { while (b) { a %= b; swap (a, b); } return a; }

template<typename T> void read(T& a) { a = input<T>(); }
template<typename T> void read(T& a, T& b) { read(a), read(b); }
template<typename T> void read(T& a, T& b, T& c) { read(a, b), read(c); }
template<typename T> void read(T& a, T& b, T& c, T& d) { read(a, b), read(c, d); }

const int inf = 1e9 + 20;
const short short_inf = 3e4 + 20;
const long double eps = 1e-12;
const int maxn = (int)2e3 + 12, base = 1e9 + 7;
const ll llinf = 2e18 + 5;

template<typename T>
T binpow(T n, T s)
{
    if (s <= 0)
        return 1LL;
    if (s % 2 == 0){
        T b = binpow(n, s / 2);
        return ( 1LL * b * b ) % base;
    } else {
        return (1LL* binpow(n, s - 1) * n) % base;
    }
}

ll gcd (ll a, ll b, ll & x, ll & y) {
	if (a == 0) {
		x = 0; y = 1;
		return b;
	}
	ll x1, y1;
	ll d = gcd (b%a, a, x1, y1);
	x = y1 - (b / a) * x1;
	y = x1;
	return d;
}

bool find_any_solution (ll a, ll b, ll c, ll & x0, ll & y0, ll & g) {
	g = gcd (abs(a), abs(b), x0, y0);
	if (c % g != 0)
		return false;
	x0 *= c / g;
	y0 *= c / g;
	if (a < 0)   x0 *= -1;
	if (b < 0)   y0 *= -1;
	return true;
}

void shift_solution (ll & x, ll & y, ll a, ll b, ll cnt) {
	x += cnt * b;
	y -= cnt * a;
}

ll be = -1;

void find_all_solutions (ll a, ll b, ll c, ll minx, ll maxx, ll miny, ll maxy, ll add) {
	ll x, y, g;
	if (! find_any_solution (a, b, c, x, y, g))
		return;
	a /= g;  b /= g;

	ll sign_a = a>0 ? +1 : -1;
	ll sign_b = b>0 ? +1 : -1;

	shift_solution (x, y, a, b, (minx - x) / b);
	if (x < minx)
		shift_solution (x, y, a, b, sign_b);
	if (x > maxx)
		return;
	ll lx1 = x;

	shift_solution (x, y, a, b, (maxx - x) / b);
	if (x > maxx)
		shift_solution (x, y, a, b, -sign_b);
	ll rx1 = x;

	shift_solution (x, y, a, b, - (miny - y) / a);
	if (y < miny)
		shift_solution (x, y, a, b, -sign_a);
	if (y > maxy)
		return;

	ll lx2 = x;

	shift_solution (x, y, a, b, - (maxy - y) / a);
	if (y > maxy)
		shift_solution (x, y, a, b, sign_a);
	ll rx2 = x;
	if (lx2 > rx2)
		swap (lx2, rx2);
	ll lx = max (lx1, lx2);
	ll rx = min (rx1, rx2);

	if (lx > rx)
		return;

	// cerr << b << endl;
	ll ly = (c - a * lx) / b; // check a , b, c
	ll ry = (c - a * rx) / b;

	if (lx + ly + add > be) be = lx + ly + add;
	if (rx + ry + add > be) be = rx + ry + add;

	return;
}

ll dist(ll l, ll r, ll n) {
	if (l <= r) return r - l + 1;
	return r - l + 1 + n;
}

int main() {
	// files1;
	fast_io;

	ll n, l, r, k;
	cin >> n >> l >> r >> k;

	ll d = dist(l, r, n);
	if (n <= 10000) {
		int be = -1;
		int N = n;
		int D = d;
		for (int a = 0; a <= D; a++)
			for (int b = 0; b <= N - D; b++) {
				if (k < a + D) break;
				if ((k - a - D) % (a + b + N) == 0) {
					if (be < a + b) be = a + b;
				}
			}
		for (int a = 0; a < D; a++)
			for (int b = 0; b <= N - D; b++) {
				if (k < a + D) break;
				if ((k - a - D) % (a + 1 + b + N) == 0) {
					if (be < (a + b + 1)) be = a + b + 1;
				}
			}
		cout << be << "\n";
		return 0;
	}

	if (d <= k && 2 * d >= k) {
		ll a = min(d, k - d + 1);
		be = a + n - d;
	}

	// cout << d << endl;

	ll lmin = max(1ll, k / (2 * n) - 5);
	ll lmax = k / n + 5;

	// cout << lmin << ' ' << lmax << endl;

	for (ll l = lmin; l <= lmax; l++) {
		ll c = k - d - l * n;
		if (c < 0) break;
		find_all_solutions(l + 1, l, c, 0, d, 0, n - d, 0);

		c -= l;
		if (c >= 0) {
			find_all_solutions(l + 1, l, c, 0, d - 1, 0, n - d, 1);
		}
	}

	cout << be << endl;
	return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

    if (K < Q) {
        cout << "-1\n";
        return;
    }

    ll ans = -1;

    if (K <= 2*Q) {
        cout << min(N, K-Q + 1 + (N-Q)) << endl;
        return;
    }

    for (ll rev = 1; rev <= 1000000; ++rev) {
        ll take = (K-Q+N + N-Q+1)/(rev+1);
        if (take < N || take > 2 * N) continue;
        ll s = take - N;
        ll left = (K - Q) - rev * take;
        if (left < 0 || left > min(Q,s)) continue;
        if (min(Q, left + 1) + (N - Q) < s) continue;
        ans = max(ans, s);

    }

    for (ll take = 1; take <= 1000000; ++take) {
        if (take < N || take > 2 * N) continue;
        ll s = take - N;
        for (ll rev = (K - 2*Q) / take; rev <= (K-Q) / take ; ++rev) {
            if (rev <= 0) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0 || left > min(Q,s)) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

    if (K < Q) {
        cout << "-1\n";
        return;
    }

    ll ans = -1;

    if (K <= 2*Q) {
        cout << min(N, K-Q + 1 + (N-Q)) << endl;
        return;
    }

    auto check = [&](ll rev, ll take) {
        ll s = take - N;
        ll left = (K - Q) - rev * take;
        if (take >= N && take <= 2*N && left >= 0 && left <= min(Q,s) && min(Q, left + 1) + (N - Q) >= s)
            ans = max(ans, s);
    };

    for (ll rev = 1; rev <= 1000000; ++rev) {
        check(rev, (K-Q+N + N-Q+1)/(rev+1));
    }

    for (ll take = 1; take <= 1000000; ++take) {
        check((K - 2*Q) / take, take);
        check((K - 2*Q) / take + 1, take);
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <list>
#include <cassert>
#include <climits>
using namespace std;

#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define FORSZ(i,a,v) FOR(i,a,SZ(v))
#define REPSZ(i,v) REP(i,SZ(v))
typedef long long ll;
int gcd(int a,int b) { return b==0?a:gcd(b,a%b); }

ll n,l,r,k;

ll solve() {
	if(l==r&&k<=2) return n;
	ll ret=-1;
	ll last=l<=r?r-l:n+r-l;
	FORE(bfin,1,2) if(bfin<=k) REP(nb,2) {
		if(bfin==2&&nb==0) continue;
		// max na+nb+nc s.t. nfull*(n+na+nb+nc)+(last+na)=k-bfin, nfull>=0, 0<=na<=last, 0<=nc<=n-last-1
		if(k/n<n) {
			// suppose we know nfull, then (na+nc)*nfull+na=k-bfin-nfull*n-nfull*nb-last, (na+nc)<=na+n-last-1
			for(ll nfull=0;;++nfull) {
				ll rhs=k-bfin-nfull*(n+nb)-last; if(rhs<0) break;
				if(nfull==0) {
					if(rhs<=last) { ll na=rhs,nc=n-last-1; ret=max(ret,na+nb+nc); }
				} else {
					ll nac=min(n-1,rhs/nfull),na=rhs-nac*nfull; if(nac<na||na>last) continue;
					// 0<=(nac-x)-(na+x*nfull)<=n-last-1, na+x*nfull<=last
					// x<=(nac-na)/(nfull+1), x<=(last-na)/nfull, x>=(nac-na-(n-last-1))/(nfull+1)
					ll xmn=nac-na-(n-last-1)<0?0:(nac-na-(n-last-1)+nfull)/(nfull+1),xmx=min((nac-na)/(nfull+1),(last-na)/nfull);
					if(xmn<=xmx) ret=max(ret,nac-xmn+nb);
				}
			}
		} else {
			// suppose we know nac=na+nc, then nfull=floor((k-bfin-last)/(n+na+nb+nc)), na=k-bfin-nfull*(n+na+nb+nc)-last
			for(ll nac=0;nac<=n-1;++nac) {
				ll nfull=(k-bfin-last)/(n+nac+nb);
				ll na=k-bfin-nfull*(n+nac+nb)-last,nc=nac-na;
				if(0<=na&&na<=last&&0<=nc&&nc<=n-last-1) ret=max(ret,nac+nb);
			}
		}
	}
	return ret;
}

void run() {
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	printf("%lld\n",solve());
}

void stress() {
	for(n=1;n<=16;++n) {
		for(k=1;k<=1000;++k) {
			vector<ll> ans(n,-1);
			REP(mask,1<<n) {
				ll each=n; REP(i,n) if(mask&(1<<i)) ++each;
				ll rem=k%each; if(rem==0) rem=each;
				REP(i,n) { ll cur=min(rem,mask&(1<<i)?2LL:1LL); rem-=cur; if(rem==0) { ans[i]=max(ans[i],each-n); break; } } assert(rem==0);
			}
			for(l=1,r=1;r<=n;++r) {
				ll have=solve(),want=ans[r-1];
				if(have==want) { printf("."); continue; }
				printf("err\n");
				printf("n=%lld k=%lld l=%lld r=%lld have=%lld want=%lld\n",n,k,l,r,have,want);
				exit(0);
			}
		}
	}
}

int main() {
	run();
	//stress();
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define MAXN 1000009
#define MAXT 8000009
#define MOD 1000000007
#define INF 10000000000000009LL
#define EPS 1e-7
#define FOR(x,n) for(int x=0; x<n; x++)
#define FOR1e(x,n) for(int x=1; x<=n; x++)
#define pb push_back
#define sz(x) int(x.size())
#define all(x) x.begin(), x.end()
typedef pair<int, int> ii;
typedef long long ll;

ll solve1(ll n, ll d, ll k) {
	ll ans = -1;
	for (ll x = 0; x <= n; x++) {
		for (ll y = max(x+d-n, 0LL); y <= min(d, x); y++) {
			ll k2 = k - d - y;

			if (k2 >= 0 && k2%(n+x) == 0) { ans = x; }
			if (y > 0 && k2 + 1 >= 0 && (k2+1)%(n+x) == 0) ans = x;
		}
	}
	return ans;
}

ll solve2(ll n, ll d, ll k) {
	ll ans = -1;
	for (ll r = 0; r <= k/n; r++) {
		ll k2 = k - d - n*r;
		if (r == 0) {
			if (k2 < 0) continue;
			else if (k2 <= d-1) ans = max(ans, n-d + (k2 + 1));
			else if (k2 == d) ans = max(ans, n);
			continue;
		}

		if (k2 >= 0) {
			ll x1, x2, x;
			x1 = k2/r;
			x2 = (k2 + n - d)/(r+1);
			x = min(n, min(x1, x2));

			if (k2 - r*x <= d && k2 - r*x <= x) {
				ans = max(ans, x);
			}
		}
		k2++;
		if (k2 >= 0) {
			ll x1, x2, x;
			x1 = (k2-1)/r;
			x2 = (k2 + n - d)/(r+1);
			x = min(n, min(x1, x2));

			if (k2 - r*x <= d && k2 - r*x <= x) {
				ans = max(ans, x);
			}
		}
	}
	return ans;
}

int main() {
	ll n, l, r, k;

	cin >> n >> l >> r >> k;
	l--; r--;
	ll d = (n+r-l)%n + 1;

	if (n <= 5000) {
		cout << solve1(n, d, k) << "\n";
	} else cout << solve2(n, d, k) << "\n";
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mem(a) memset(a,0,sizeof a)
#define pii pair<int,int>
const int N=1e5+5;
const int INF=1e9+5;
ll read(ll &a){scanf("%lld",&a);return a;}
int read(int &a){scanf("%d",&a);return a;}
int read(){int a;scanf("%d",&a);return a;}
int read(int &a,int &b){scanf("%d %d",&a,&b);return a;}
int main()
{
    ll n,l,r,k,x,ans=-1;
    cin>>n>>l>>r>>k;
    x=(n+r-l)%n+1;
    if(n<=3e6){
        for(ll i=n;i>=0;i--){
            ll z=(k-1)%(i+n)-x+1;
            ll p=z+1;
            if(z<0||z>x||z>i||x-z>n-i+1)continue;
            if((p<=i&&p<=x)||x-z<=n-i){
                ans=i;
                break;
            }
        }
    }
    else{
        ll t=k/n;
        for(ll i=0;i<=t;i++){
            ll res=(k-2*x-n*(i-1)+1)/(i+1);
            ll z=k-i*(res+n)-x,a;
            if(z<0){
                a=ceil((-z)*1.0/i);
                if(a*i+z<=res-a&&a*i+z<=x)ans=max(ans,res-a);
            }
            else if(res<=n){
                if(z>=0&&z<=x&&z<=res)ans=max(ans,res);
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

#include<bits/stdc++.h>

#define LL long long
#define RG register

using namespace std;
template<class T> T gi() {
	T x = 0; bool f = 0; char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = 1, c = getchar();
	while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return f ? -x : x;
}
LL n, l, r, k, len;
namespace cpp1 {
	bool check(LL x) {
		LL tmp = k % (x + n), x1 = tmp - len;
		if (x1 < 0) return 0;
		if (x1 < min(x, len)) x1++;
		if (x1 <= min(x, len) && x - x1 <= n - len) return 1;
		return 0;
	}
	void main() {
		for (int i = n; i >= 0; i--)
			if (check(i)) { printf("%d\n", i); return ; }
		puts("-1");
		return ;
	}
}
namespace cpp2 {
	void main() {
		len = (r - l + n) % n + 1;
		LL ans = -1;
		for (LL i = 0; i <= k/n; i++) {
            LL p = (k - 2*len - (i-1)*n + 1) / (i+1);
            LL y = k - i*(n+p) - len;
            if (y < 0) {
                if (i == 0)
                    continue;
                LL dis = (-y - 1) / i + 1;
                y += i*dis;
                p -= dis;
            }
            if (p > n) {
                y += (p-n) * i;
            }
            if (y < 0 || y > p || y > len || len-(y+1) > n-p)
                continue;
            LL y2 = y+1;
            if (y2 <= p && y2 <= len) {
                ans = max(ans , p);
            }
            if (len-y <= n-p) {
                ans = max(ans, p);
            }
        }
		printf("%lld\n", ans);
	}
}
int main() {
	//freopen(".in", "r", stdin);
	//freopen(".out", "w", stdout);
	n = gi<LL>(), l = gi<LL>(), r = gi<LL>(), k = gi<LL>();
	len = (r - l + 1) % n;
	if (len < 0) len += n;
	if (n <= 2e6) cpp1 :: main();
	else cpp2 :: main();
	return 0;
}

#include<stdio.h>
#define it register int
#define ct const int
#define il inline
typedef long long ll;
#define rll register ll
#define cll const ll
const int N=1000005;
const ll inf=9e18;
ll n,l,r,k,L,R,ans;
template<class I>
il I Max(I p,I q){return p>q?p:q;}
template<class I>
il I Min(I p,I q){return p<q?p:q;}
il void solve(cll K){
	cll k=::k-K;
	if(n<k/n){
		if(k<L) return;
		for(rll i=n;~i;--i){
			cll x=R+i;
			cll b=Max((k-L-Min(b,L-1)+x-1)/x,0ll),a=k-L-b*x;
			if(i>=K&&a>=0&&a<=i&&a<L&&i<=R-L+1+a) ans=Max(ans,i);
		}
		return ;
	}
	for(rll i=0;i*R<=k;++i){
		cll w=k-i*R-L;
		if(w<0||(i==0&&w>L-1)) continue;
		cll b=Min(R,Min((w+R-L+1)/(i+1),i?w/i:inf)),a=w-b*i;
		if(b>=K&&a>=0&&a<=b&&a<L&&b<=R-L+1+a) ans=Max(ans,b);
	}
}
int main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);R=n;L=r-l+1,L<=0?L+=n:0,ans=-1;
	solve(0),solve(1),printf("%lld",ans);//最后一个人只拿一个
	return 0;
}

#include <bits/stdc++.h>
#define LL long long
using namespace std;
LL n,x,k,lb,ub,l,r,ans=-1;
int main() {
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	x=(r>=l?r-l+1:r+n-l+1)%n;
	for(LL i=k,j,r;i;i=j){
		j=k/(k/i+1);r=k/i;
		ub=min(2*n,i);
		lb=max(n,j+1);
		ub=min(ub,min((2*n+k-2*x+1)/(r+1),(k-x)/r));
		lb=max(lb,(k-2*x+r-1)/r);
		if(ub>=lb)ans=max(ans,ub);
	}
	if(x<=k&&k<=x*2)ans=max(ans,n+min(k-x,x-1)+n-x+1);
	if(!x&&k==n)ans=max(ans,n+1);
	printf("%lld\n",~ans?ans-n:ans);
}

#include<bits/stdc++.h>
#define max(a,b) (((a)>(b))?(a):(b))
#define min(a,b) (((a)<(b))?(a):(b))
#define LL long long
using namespace std;
template<typename T>void read(T &x){
	x=0;int f=1;
	char c=getchar();
	for(;!isdigit(c);c=getchar()) if (c=='-') f=-1;
	for(;isdigit(c);c=getchar()) x=x*10+c-48;
	x*=f;
}
LL n,l,r,k;
LL ans=-1;
int main(){
	read(n);read(l);read(r);read(k);
	LL len=r-l+1;
	if(len<=0) len+=n;
	if(n<=12000){
		for(LL i=0;i<=len-1;++i)
			for(LL j=0;j<=n-len;++j){
				//r==1
				LL kk=k-1;
				kk%=i+j+n;
				kk++;
				if(kk==i+len) ans=max(ans,i+j);
				//r==2
				kk=k-1;kk%=i+j+1+n;kk++;
				if(kk==i+len||kk==i+len+1) ans=max(ans,i+j+1);
			}
	}
	else{
		LL lim=k/n;
		//c==0
		if(k<=2*len&&k>=len) ans=max(ans,n-len+min((k-len+1),len));
		for(LL t=1;t<=lim;++t){
			//eat 2
			LL kk=k-t*n-len;
			LL a0=kk-t;
			LL b0=1-a0;
			LL zl=max(ceil((a0-len)/(double)t),ceil(-b0/(double)(t+1)));
			LL zr=min(floor(a0/(double)t),floor((n-len-b0)/(double)(t+1)));
			if(zl<=zr){
				ans=max(ans,a0-t*zl+b0+(t+1)*zl);
				ans=max(ans,a0-t*zr+b0+(t+1)*zr);
			}
			//eat 1
			 kk=k-t*n-len+1;
			 a0=kk-t;
			 b0=1-a0;
			 zl=max(ceil((a0-len)/(double)t),ceil(-b0/(double)(t+1)));
			 zr=min(floor((a0-1)/(double)t),floor((n-len-b0)/(double)(t+1)));
			if(zl<=zr){
				ans=max(ans,a0-t*zl+b0+(t+1)*zl);
				ans=max(ans,a0-t*zr+b0+(t+1)*zr);
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}

//#pragma GCC diagnostic error "-std=c++11"
#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<bits/stdc++.h>
using namespace std;

#define ll long long
namespace exgcd{
  ll gao(ll a,ll b,ll &x,ll &y){
    if (b==0){
      x=1; y=0; return a;
    }
    ll k=gao(b,a%b,x,y);
    ll t=x; x=y; y=t-a/b*y;
    return k;
  }
  ll inv(ll a,ll mod){
    ll x, y; ll d=gao(a,mod,x,y);
    return d==1? (x%mod+mod)%mod: -1;
  }
  ll minx(ll a,ll b,ll c){
    ll x, y; ll g=gao(a,b,x,y);
    if (c%g) assert(0);
    a/=g; b/=g; c/=g;
    x*=c; y*=c;
    x%=b; while (x<=0) x+=b;
    return x;
  }
  bool fuck(ll a,ll b,ll c,ll lx,ll ly,ll &x,ll &y){
    ll g=gao(a,b,x,y);
    if (c%g) assert(0);
    a/=g; b/=g; c/=g;
    x*=c; y*=c;
    x=x%b-b-b+lx/b*b;
    while (x+b<=lx) x+=b; if (x<0) return 0;
    y=(c-a*x)/b;
    if (y>=0&&y<=ly) return 1;
    if (y>ly) return 0;
    ll d=(abs(y)+a-1)/a;
    y+=d*a; x-=d*b;
    return x>=0&&x<=lx&&y>=0&&y<=ly;
  }
}

ll n, d, k, x, y, ans=-1;

void doit(ll t){
  if (t<0) return;
  if (t==0){
    if (k>=d&&k<=2*d){
      ans=max(ans,(k-d==d? d: k-d+1)+n-d);
    }
    return;
  }
  ll aim=k-t*n-d;
  if (exgcd::fuck(t,t+1,aim,n-d,d,x,y)){
    ans=max(ans,x+y);
  }
}

void doit2(ll t){
  if (t<=0) return;
  ll aim=k-t*n-d;
  if (exgcd::fuck(t,t+1,aim,n-d,d,x,y)){
    if (!y) x-=t+1, y+=t;
    if (x>=0&&x<=n-d&&y>=0&&y<=d){
      ans=max(ans,x+y);
    }
  }
}

int main(){
  cin>>n>>x>>y>>k;
  d= y>=x? y-x+1: y+n-x+1;
  doit(0);
  for (ll i=n, nex;i<=n*2;i=nex+1){
    ll t=k/i; nex= t==0? 1e18: k/t;
    doit(t-1); doit(t); doit(t+1);
  }
  ++k;
  for (ll i=n, nex;i<=n*2;i=nex+1){
    ll t=k/i; nex= t==0? 1e18: k/t;
    doit2(t-1); doit2(t); doit2(t+1);
  }
  cout<<ans<<endl;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,x,k,lb,ub,ans=-1;
int main() {
	ll l,r;
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	x=(r>=l?r-l+1:r+n-l+1)%n;
	for(ll i=k,j,r;i;i=j){
		j=k/(k/i+1);r=k/i;
		ub=min(2*n,i);
		lb=max(n,j+1);
		ub=min(ub,min((2*n+k-2*x+1)/(r+1),(k-x)/r));
		lb=max(lb,(k-2*x+r-1)/r);
		if(ub>=lb)ans=max(ans,ub);
	}
	if(x<=k&&k<=x*2)ans=max(ans,n+min(k-x,x-1)+n-x+1);
	if(!x&&k==n)ans=max(ans,n+1);
	printf("%lld\n",~ans?ans-n:ans);
}

#include "bits/stdc++.h"

using namespace std;

typedef long long LL;
typedef unsigned long long ULL;

typedef long double ld;

const ld eps = 1e-9;
const ld pi = acos(-1);

//#define ENABLE_FREAD

namespace io_impl
{
	inline bool maybe_digit(char c)
	{
		return c >= '0' && c <= '9';
	}

	struct io_s
	{
	private:
		FILE* fin = stdin;
		FILE* fout = stdout;

		bool negative;
		bool ok = true;
		char ch;

		int precious;
		long double epslion;

#ifdef ENABLE_FREAD
		inline char next_char() {
			static char buf[100000], *p1 = buf, *p2 = buf;
			return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, fin), p1 == p2) ? EOF : *p1++;
		}
#else
		char next_char() const
		{
			return fgetc(fin);
		}
#endif
	public:
		void init()
		{
			ch = next_char();
		}

		void init(FILE* _in, FILE* _out)
		{
			fin = _in;
			fout = _out;
			init();
		}

#pragma region read int

		template <typename T>
		bool rn(T& _v)
		{
			negative = false;
			_v = 0;
			while (!maybe_digit(ch) && ch != EOF)
			{
				negative = ch == '-';
				ch = next_char();
			}
			if (ch == EOF)return ok = false;
			do
			{
				_v = (_v << 1) + (_v << 3) + ch - '0';
			}
			while (maybe_digit(ch = next_char()));
			if (negative) _v = -_v;
			return true;
		}

		template <typename T>
		void rn_unsafe(T& _v)
		{
			negative = false;
			_v = 0;
			while (!maybe_digit(ch))
			{
				negative = ch == '-';
				ch = next_char();
			}
			do
			{
				_v = (_v << 1) + (_v << 3) + ch - '0';
			}
			while (maybe_digit(ch = next_char()));
			if (negative) _v = -_v;
		}

		template <typename T>
		T rn()
		{
			T v = T();
			rn_unsafe(v);
			return v;
		}

#pragma endregion

#pragma region read unsigned

		template <typename T>
		bool run(T& _v)
		{
			_v = 0;
			while (!maybe_digit(ch) && ch != EOF) ch = next_char();
			if (ch == EOF)return ok = false;
			do
			{
				_v = (_v << 1) + (_v << 3) + ch - '0';
			}
			while (maybe_digit(ch = next_char()));
			return true;
		}

		template <typename T>
		void run_unsafe(T& _v)
		{
			_v = 0;
			while (!maybe_digit(ch)) ch = next_char();
			do
			{
				_v = (_v << 1) + (_v << 3) + ch - '0';
			}
			while (maybe_digit(ch = next_char()));
		}

		template <typename T>
		T run()
		{
			T v = T();
			run_unsafe(v);
			return v;
		}

#pragma endregion

#pragma region read float

		template <typename T>
		bool rd(T& _v)
		{
			negative = false;
			_v = 0;
			while (!maybe_digit(ch) && ch != EOF)
			{
				negative = ch == '-';
				ch = next_char();
			}
			if (ch == EOF)return ok = false;
			do
			{
				_v = (_v * 10) + (ch - '0');
			}
			while (maybe_digit(ch = next_char()));
			static int stk[70], tp;
			if (ch == '.')
			{
				tp = 0;
				T _v2 = 0;
				while (maybe_digit(ch = next_char()))
				{
					stk[tp++] = ch - '0';
				}
				while (tp--)
				{
					_v2 = _v2 / 10 + stk[tp];
				}
				_v += _v2 / 10;
			}
			if (ch == 'e' || ch == 'E')
			{
				ch = next_char();
				static bool _neg = false;
				if (ch == '+') ch = next_char();
				else if (ch == '-') _neg = true, ch = next_char();
				if (maybe_digit(ch))
				{
					_v *= pow(10, run<LL>() * (_neg ? -1 : 1));
				}
			}
			if (negative) _v = -_v;
			return true;
		}

		template <typename T>
		T rd()
		{
			T v = T();
			rd(v);
			return v;
		}

#pragma endregion

#pragma region read string

		int gets(char* s)
		{
			char* c = s;
			while (ch == '\n' || ch == '\r' || ch == ' ') ch = next_char();
			if (ch == EOF) return (ok = false), *c = 0;
			do
			{
				*(c++) = ch;
				ch = next_char();
			}
			while (ch != '\n' && ch != '\r' && ch != ' ' && ch != EOF);
			*(c++) = '\0';
			return static_cast<int>(c - s - 1);
		}

		int getline(char* s)
		{
			char* c = s;
			while (ch == '\n' || ch == '\r') ch = next_char();
			if (ch == EOF) return (ok = false), *c = 0;
			do
			{
				*(c++) = ch;
				ch = next_char();
			}
			while (ch != '\n' && ch != '\r' && ch != EOF);
			*(c++) = '\0';
			return static_cast<int>(c - s - 1);
		}

		char get_alpha()
		{
			while (!isalpha(ch)) ch = next_char();
			const char ret = ch;
			ch = next_char();
			return ret;
		}

		char get_nonblank()
		{
			while (iswspace(ch)) ch = next_char();
			const char ret = ch;
			ch = next_char();
			return ret;
		}

		char get_char()
		{
			const char ret = ch;
			ch = next_char();
			return ret;
		}

		template <typename T>
		void o(T p)
		{
			static int stk[70], tp;
			if (p == 0)
			{
				putchar('0');
				return;
			}
			if (p < 0)
			{
				p = -p;
				putchar('-');
			}
			while (p) stk[++tp] = p % 10, p /= 10;
			while (tp) putchar(stk[tp--] + '0');
		}

		template <typename T>
		void od(T v)
		{
			static int stk[70], tp;
			tp = 0;
			if (fabs(v) < epslion / 10)
			{
				putchar('0');
				if (precious > 0)
				{
					putchar('.');
					for (int i = 0; i < precious; ++i) putchar('0');
				}
				return;
			}
			if (v < 0)
			{
				v = -v;
				putchar('-');
			}
			v += epslion / 2;
			T p = floor(v) + epslion / 10;
			while (fabs(p) > 1 - epslion)
			{
				stk[++tp] = fmod(p, 10), p = floor(p / 10) + epslion;
			}
			if (tp == 0) putchar('0');
			while (tp) putchar(stk[tp--] + '0');
			if (precious == 0) return;
			putchar('.');
			v -= floor(v);
			for (int i = 0; i < precious; ++i)
			{
				v *= 10;
				putchar((int)floor(v) + '0');
				v = fmod(v, 1);
			}
		}

#pragma endregion

#pragma region enhancement

		typedef void io_operator_func(io_s& v);
		typedef char* charptr;

		template <typename T>
		io_s& operator >>(T& x)
		{
			if (numeric_limits<T>::is_signed) rn(x);
			else run(x);
			return *this;
		}

		template <typename TFirst, typename TSecond>
		io_s& operator >>(pair<TFirst, TSecond>& pr)
		{
			*this >> pr.first >> pr.second;
			return *this;
		}

		template <typename T>
		io_s& operator <<(const T& x);

		io_s& operator <<(const io_operator_func*& x)
		{
			x(*this);
			return *this;
		}

		operator bool() const { return ok; }

		void set_precious(int x)
		{
			precious = x;
			epslion = pow(10, -x);
		}

		int ri() { return rn<int>(); }
		LL rll() { return rn<LL>(); }

		static void new_line(io_s& v)
		{
			putchar('\n');
		}

		static void flush(io_s& v)
		{
			fflush(stdout);
		}
#pragma endregion

#pragma region batch

		template <typename T>
		void o(T begin, T end)
		{
			while (begin != end)
			{
				o(*begin++);
				o(begin == end ? '\n' : ' ');
			}
		}

#pragma endregion
	};

#pragma region input fix

	template <>
	inline io_s& io_s::operator >>(char*& x)
	{
		gets(x);
		return *this;
	}

	template <>
	inline io_s& io_s::operator >>(char& x)
	{
		x = get_nonblank();
		return *this;
	}

	template <>
	inline io_s& io_s::operator >>(float& x)
	{
		rd(x);
		return *this;
	}

	template <>
	inline io_s& io_s::operator >>(double& x)
	{
		rd(x);
		return *this;
	}

	template <>
	inline io_s& io_s::operator >>(long double& x)
	{
		rd(x);
		return *this;
	}
#pragma region output fix

	template <>
	inline void io_s::o(const char p)
	{
		putchar(p);
	}

	template <>
	inline void io_s::o(const char* p)
	{
		printf(p);
	}

	template <>
	inline void io_s::o(float p)
	{
		od(p);
	}

	template <>
	inline void io_s::o(double p)
	{
		od(p);
	}

	template <>
	inline void io_s::o(long double p)
	{
		od(p);
	}

	template <typename T>
	io_s& io_s::operator <<(const T& x)
	{
		o(x);
		return *this;
	}

	io_s::io_operator_func* nl = io_s::new_line;
	io_s::io_operator_func* fl = io_s::flush;
#pragma endregion
}

using namespace io_impl;

io_s io;

typedef void InitFunction();
typedef bool SolveFunction(int);

struct env_s
{
private:
	bool global_inited = false;

	bool case_inited = false;
public:
	bool once()
	{
		return global_inited ? false : (global_inited = true);
	}

	bool every()
	{
		return case_inited ? false : (case_inited = true);
	}

	InitFunction *_initOnce, *_init;

	template <InitFunction TInitOnce, InitFunction TInit>
	void configure()
	{
		_initOnce = TInitOnce;
		_init = TInit;
	}

	void init(bool global)
	{
		if (global) if (_initOnce != nullptr)_initOnce();
		if (_init != nullptr) _init();
	}

	void empty_init()
	{
	}

	template <SolveFunction TSolve>
	void solve_single()
	{
		global_inited = false;
		case_inited = false;
		init(true);
		TSolve(0);
	}

	template <SolveFunction TSolve>
	void solve_many()
	{
		global_inited = false;
		int T = io.ri();
		for (int cs = 1; T--; ++cs)
		{
			case_inited = false;
			init(cs == 1);
			if (!TSolve(cs))break;
		}
	}

	template <SolveFunction TSolve>
	void solve_much()
	{
		global_inited = false;
		case_inited = false;
		for (int cs = 1; init(cs == 1), TSolve(cs); ++cs)
			case_inited = false;
	}
} env;

#define FOR(i, x, y) for (decay<decltype(y)>::type i = (x), _##i = (y); i < _##i; ++i)
#define FORD(i, x, y) for (decay<decltype(y)>::type i = (x), _##i = (y); i > _##i; --i)
#ifdef _DEBUG
#define dbg(...) do { cerr << "Debug: " << # __VA_ARGS__ << " -> "; err(## __VA_ARGS__); } while (0)
#define fuck(x) do { printf("fuck@%d\n", x); } while(0)
#else
#define dbg(...)
#define fuck(...)
#endif
void err() { cerr << endl; }

template <typename T, typename... Args>
void err(T a, Args ... args)
{
	cerr << a << ' ';
	err(args...);
}

// ----------------------------------------------------------------

namespace solution
{
#pragma region init

	void init_once()
	{
		srand(time(nullptr));
		io.set_precious(12);
		//io.set_precious(2);
	}

	void init_every()
	{
	}

#pragma endregion

	const int TH = 1e6;

	//const int TH = 0;

	bool solve(int _cas)
	{
		LL n, k, l, r, tt;
		io >> n >> l >> r >> k; tt = (r - l) % n;
		if (tt < 0)tt += n;
		++tt;
		if(n<=TH)
		{
			LL ans = -1;
			FOR(x, n, 2 * n + 1)
			{
				LL y = x - n;
				LL t = k % x; if (t == 0) t += x;
				LL lb = tt + max(y - n + tt - 1, 0LL), rb = tt + min(tt, y);
				if (lb <= t && t <= rb)
				{
					ans = x - n;
				}
			}
			io << ans << nl;
		} else
		{
			LL ans = -1;
			LL x = 2 * n;
			while(x>=n)
			{
				LL t = k / x, t2 = k % x;
				if(t2==0 && tt==n)
				{
					ans = x - n;
					break;
				}
				LL y = k / (t + 1);
				LL bx = tt + max(x - n * 2 + tt - 1, 0LL);
				LL v = max(0LL, (bx - t2 + t) / (t + 1));
				if(x-v>=y)
				{
					x -= v;
					t2 += t * v;
					if (x >= y && t2 <= tt * 2)
					{
						LL lb = tt + max(x - n * 2 + tt - 1, 0LL), rb = tt + min(tt, x - n);
						if (t2 >= lb && t2 <= rb)
						{
							ans = x - n;
							break;
						}
					}
					--x;
					t2 += t;
					if (x >= y && t2 <= tt * 2)
					{
						LL lb = tt + max(x - n * 2 + tt - 1, 0LL), rb = tt + min(tt, x - n);
						if (t2 >= lb && t2 <= rb)
						{
							ans = x - n;
							break;
						}
					}
				}
				x = y;
			}
			io << ans << nl;
		}
		return true;
	}
}

//#define DEBUGTOOL 1

#ifdef _DEBUG

#ifndef ONLINE_JUDGE

#define DEBUGTOOL 1

#endif

#endif

int main()
{
#if DEBUGTOOL
	clock_t t = clock();
	io.init();
	//io.init(fopen("data.in", "r"), stdout);
	//io.init(fopen("data.in", "r"), fopen("data.out", "w"));
#else
	io.init();
#endif
	env.configure<solution::init_once, solution::init_every>();
	env.solve_single<solution::solve>();
#if DEBUGTOOL
	io << "time: " << (clock() - t) * 0.001 << "s" << nl;
	system("pause");
#endif
	return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

    if (K < Q) {
        cout << "-1\n";
        return;
    }

    ll ans = -1;

    if (K <= 2*Q) {
        cout << min(N, K-Q + 1 + (N-Q)) << endl;
        return;
    }

    for (ll rev = 1; rev <= 1000000; ++rev) {
        for (ll take : {(K-Q+N)/(rev+1), (K-Q+N)/(rev+1), (K-Q+N)/(rev+1),
                        (K - 2*Q) / rev, (K-2*Q)/rev, (K-2*Q)/rev,
                        (2*N+K-2*Q+1)/(rev+1), (2*N+K-2*Q+1)/(rev+1), (2*N+K-2*Q+1)/(rev+1),
        }) {
            ll s = take - N;
            if (s < 0) continue;
            if (s > N) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0) continue;
            if (left > Q) continue;
            if (left > s) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    for (ll take = 1; take <= 1000000; ++take) {
        if (take < N) continue;
        if (take > 2 * N) continue;
        ll s = take - N;
        for (ll rev = (K - 2*Q) / take - 1; rev <= (K-Q) / take + 1; ++rev) {
            if (rev <= 0) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0) continue;
            if (left > Q) continue;
            if (left > s) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

#pragma region
#include <bits/stdc++.h>
using namespace std;
#define ri register int
#define il inline
#define LL long long
#define uint unsigned int
#define ull unsigned long long
#define solid const auto &
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<LL,LL>
#define fi first
#define se second
#define gm int mid((l+r)/2)
#define space putchar(' ')
#define enter putchar('\n')
#define rd() ({ri t;in(t);t;})
#define Size(x) ((int)x.size())
#define mem(x,y) memset(x,y,sizeof(x))
template<class T>il void in(T &x)
{
	x=0; char c=getchar(); bool f=0;
	while(!isdigit(c)) f|=(c=='-'),c=getchar();
	while(isdigit(c)) x=x*10+(c^'0'),c=getchar();
	f?x=-x:0;
}
template<class T>il void out(T x,const char c='\n')
{
	static short st[30]; short m=0;
	if(x<0) putchar('-'),x=-x;
	do st[++m]=x%10,x/=10; while(x);
	while(m) putchar(st[m--]|'0');
	putchar(c);
}
template<class T>il void err(const T &x,const char c='\n') {cerr<<x<<c;}
template<class T,class ...Args>il void in(T &x,Args &...args) {in(x); in(args...);}
template<class T,class ...Args>il void out(const T &x,const Args &...args) {out(x,' '); out(args...);}
template<class T,class ...Args>il void err(const T &x,const Args &...args) {err(x,' '); err(args...);}
template<class T>il void prt(T a[],int n) {for(ri i=0; i<n; ++i) out(a[i],i==n-1?'\n':' ');}
template<class T>il void clr(T a[],int n) {memset(a,0,sizeof(T)*n);}
template<class T>il void clr(T *a,T *b) {memset(a,0,sizeof(T)*(b-a));}
template<class T>il bool ckmax(T &a,const T &b) {return a<b?a=b,1:0;}
template<class T>il bool ckmin(T &a,const T &b) {return a>b?a=b,1:0;}
namespace MOD_CALC
{
const int md=66662333,inv2=(md+1)/2;
il int add(const int a,const int b) {return a+b>=md?a+b-md:a+b;}
il int sub(const int a,const int b) {return a-b<0?a-b+md:a-b;}
il int mul(const int a,const int b) {return (LL)a*b%md;}
il void inc(int &a,const int b) {(a+=b)>=md?a-=md:0;}
il void dec(int &a,const int b) {(a-=b)<0?a+=md:0;}
il int qpow(int a,int b) {int r=1; for(; b; b>>=1,a=mul(a,a)) if(b&1) r=mul(r,a); return r;}
il int qpow(int a,int b,const int p) {int r=1; for(; b; b>>=1,a=(LL)a*a%p) if(b&1) r=(LL)r*a%p; return r;}
il int mdinv(const int a) {return qpow(a,md-2);}
template<class ...Args>il int add(const int a,const int b,const Args &...args) {return add(add(a,b),args...);}
template<class ...Args>il int mul(const int a,const int b,const Args &...args) {return mul(mul(a,b),args...);}
} using namespace MOD_CALC;
namespace i207M
{
#pragma endregion

LL n,l,r,len,k;
il void gun(LL ans) {out(ans); exit(0);}
signed main()
{
#ifdef M207
	freopen("in.in","r",stdin);
	// freopen("ot.out","w",stdout);
#endif
	in(n,l,r,k); len=(l<=r?r-l+1:n-(l-r)+1);
	if(k<len) gun(-1); // WARN
	if(n<=1000000)
	{
		// for each ans
		for(LL a=n; a>=1; --a)
		{
			LL r=k%(n+a);
			if(!r)
			{
				if(len==n) gun(a);
			}
			else
			{
				LL b=r-len;
				if(b>=0&&b<=len&&b>=a-(n-len)&&b<=a) gun(a);
			}
			r=(k+1)%(n+a);
			if(!r)
			{
				if(len==n) gun(a);
			}
			else
			{
				LL b=r-len;
				if(b>0&&b<=len&&b>=a-(n-len)&&b<=a) gun(a);
			}
		}
		if(k%n==len) gun(0);
		gun(-1);
	}
	else
	{
		// for each circle
		LL ans=-1;
		// special for 0
		if(k+1<=2*len) ckmax(ans,k+1-len+n-len); // WARN
		else if(k<=2*len) ckmax(ans,k-len+n-len);
		for(LL c=1; len+c*n<=k; ++c)
		{
			LL t=k-len-c*n,a=t/c,b=t-a*c,d=max(a-n,0ll); // WARN
			a-=d,b+=d*c;
			if(a>b+n-len)
			{
				LL w=(a-b-n+len+c)/(c+1); // WARN
				a-=w,b+=w*c;
			}
			if(b<=a&&b<=len&&a>=0) ckmax(ans,a);
		}
		for(LL c=1; len+c*n<=k+1; ++c)
		{
			LL t=k+1-len-c*n,a=t/c,b=t-a*c,d=max(a-n,0ll);
			if(b==0) ckmax(d,1ll);
			a-=d,b+=d*c;
			if(a>b+n-len)
			{
				LL w=(a-b-n+len+c)/(c+1);
				a-=w,b+=w*c;
			}
			if(b>0&&b<=a&&b<=len&&a>=0) ckmax(ans,a);
		}
		gun(ans);
	}
	return 0;
}
#pragma region
}
signed main()
{
	i207M::main();
	return 0;
}
#pragma endregion

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll ans = -1;

int main() {
    ll n, k, l, r;
    cin >> n >> l >> r >> k ;
    ll len = (l <= r ? (r - l + 1) : (n - l + 1 + r));
    if (n <= 1000000) {
        for (int i = n; i <= 2 * n; i ++ ) {
            ll s = k % i;
            if(!s) {
                s = i;
            }
            s -= len;
            ll l1 = max(i - n - (n - len) - 1, 0ll);
            ll l2 = min(len, i - n);
            if (s >= l1 && s <= l2) {
                ans = max(ans, i - n);
            }
        }
    }
    else {
        if (k >= len && k <= 2 * len) {
            ans = max(ans, (k == 2 * len) ? n : n - len + k - len + 1);
        }
        for (int i = 1; i <= k / n; i ++ ) {
            ll s2 = min((k - 2 * len + 2 * n + 1) / (i + 1), (k - len) / i);
            ll s1 = max((k - 2 * len + i - 1) / i, (k - len + n + i) / (i + 1));
            if (s1 <= s2) {
                ans = max(ans, s2 - n);
            }
        }
    }
   cout << ans << endl ;
   return 0;
}

#include<bits/stdc++.h>
#define int long long
using namespace std;

inline int read()
{
    int x=0,f=1;char ch=getchar();
    for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1;
    for (;ch>='0'&&ch<='9';ch=getchar()) x=(x<<1)+(x<<3)+ch-'0';
    return x*f;
}

signed main()
{
	int n=read(), l=read(), r=read(), k=read(), len=(n-l+r)%n+1, ans=-1;
	if (n<=1e6)
	{
		for (int i=n; i<=n<<1; i++)
		{
			int s=((k%i)?k%i:i)-len;
			if (s<=min(len, i-n)&&s>=max(i-(n<<1)+len-1, 0ll))
				ans=max(ans, i-n);
        }
    }
    else
    {
        if(k>=len && k<=2*len) ans=k==2*len?n:n-2*len+k+1;
        for(int i=1; i<=k/n; i++)
        {
            int s2=min((k-2*len+2*n+1)/(i+1),(k-len)/i);
            int s1=max((k-2*len+i-1)/i,(k-len+n+i)/(i+1));
            ans=max(ans,(s1<=s2?1:-1)*s2-n);
        }
    }
	printf("%lld\n", ans);
	return 0;
}

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,x,k,lb,ub,l,r,ans=-1;
int main(){
cin>>n>>l>>r>>k;
x=(r>=l?r-l+1:r+n-l+1)%n;
for(ll i=k,j,r;i;i=j){
j=k/(k/i+1);r=k/i;
ub=min(2*n,i);
lb=max(n,j+1);
ub=min(ub,min((2*n+k-2*x+1)/(r+1),(k-x)/r));
lb=max(lb,(k-2*x+r-1)/r);
if(ub>=lb)ans=max(ans,ub);
}
if(x<=k&&k<=x*2)ans=max(ans,n+min(k-x,x-1)+n-x+1);
if(!x&&k==n)ans=max(ans,n+1);
if(ans==-1)cout<<-1;
else cout<<ans-n;

}

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
ll n,K,l,r,ans=-1;
int main(){
	scanf("%I64d%I64d%I64d%I64d",&n,&l,&r,&K);
	ll len=(r-l+n)%n+1;
	if(n<=2e6){
		for(ll i=n,j;i>=0;i--){
			ll in=(K-len)%(n+i);
			if(len-(in+1)>n-i||in<0||in>i||in>len) continue;
			ll real=in+1;
			if(real<=i&&real<=len&&i>ans)ans=i;
			if(len-in<=n-i&&i>ans)ans=i;
			if(ans!=-1) break;
		}
	}else{
		ll up=K/n;
		for(ll r=0;r<=up;r++){
			ll i=(K-(r-1)*n+1-(len<<1))/(r+1);
			ll in=(K-r*(n+i)-len);
			if(in<0){
				if(!r) continue;
				ll res=(-in-1)/r+1;//!!!! r=0
				in+=res*r;i-=res;
			}
			if(i>n){in+=(i-n)*r;i=n;}
			if(len-(in+1)>n-i||in<0||in>i||in>len) continue;
			ll real=in+1;
			if(real<=i&&real<=len&&ans<i)ans=i;
			if(len-in<=n-i&&ans<i)ans=i;
		}
	}
	printf("%I64d\n",ans);
	return 0;
}

#include <cstdio>
//#include <cmath>
using namespace std;
int i,j;
long long n,l,k,r,sqrtn,rd,lower,upper,temp,x1,y1,ans;
long long getmax(long long a,long long b){
	if (a<b) return b;
	else return a;
}
void bis(long long l,long long rr){
	//long long mid=(l+r)>>1;

	if (l==rr){
		x1=l;
		y1=temp-x1*(long long)i;
		return;
	}
	//printf("%lld %lld$$\n",l,rr);
	x1=((l+rr)>>1)+1;
	y1=temp-x1*(long long)i;
	//printf("%lld %lld %d###\n",x1,y1,i);
	/*if (i==0){
		bis(x1,rr);
		return;
	}*/
	/*if (y1>(r-1)*2){
		bis(x1+1,rr);
		return;
	}
	if ((x1-n<y1-(r-1))||((x1-n==y1-(r-1))&&(temp=k-2))) {
		bis(x1+1,rr);
		return;
	}
	bis(l,x1);*/
	if (y1<(r-1)){
		bis(l,x1-1);
		return;
	}
	/*if ((x1==7)&&(y1==4)&&(i==1)){
		printf("?#?%lld %lld\n",x1-n,y1+(n-r+1)*2);
	}*/
	if (x1>y1+(n-r+1)*2){
		bis(l,x1-1);
		return;
	}
	bis(x1,rr);
}
long long divup(long long a,long long b){
	if (a % b==0){
		return a/b;
	}
	else return a/b+1;
}
int main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	sqrtn=10000;
	if (r<l){
		r+=n;
	}
	r=r-l+1;
	l=1;
	ans=-1;

	//sqrtn=1;

	if (n>=sqrtn){
		lower=getmax(0,(k-r*2)/(n*2));
		upper=getmax(0,(k-r)/n);
		//printf("%lld %lld##?\n",lower,upper);
		for(i=lower;i<=upper;i++){
			temp=k-1;
			bis(n,n*2);
			//y1=
			//printf("%lld %lld %d???\n",x1,y1,i);
			if ((x1>=y1-(r-1)+n)&& (x1<=y1+(n-r+1)*2) &&(y1>=r-1)&&(y1<=(r-1)*2)){
				if (x1-n>ans){
					ans=x1-n;
					//printf("!!%lld %lld %d\n",x1,y1,i);
				}
			}
			temp=k-2;
			bis(n,n*2);
			if ((x1>y1-(r-1)+n)&&(x1<=y1+(n-r+1)*2)&&(y1>=r-1)&&(y1<=(r-1)*2)){
				if (x1-n>ans){
					ans=x1-n;
					//printf("??%lld %lld %d\n",x1,y1,i);
				}
			}
			//printf("%lld %lld %d!!!\n",x1,y1,i);
		}
	}else{
		for(i=r-1;i<=(r-1)*2;i++){
			y1=i;
			temp=k-1;
			for(j=y1+(n-r+1)*2;j>=n+y1-(r-1);j--){
				if ((temp-y1) % j==0){
					if (j-n>ans) ans=j-n;
				}
			}
			temp=k-2;
			for(j=y1+(n-r+1)*2;j>n+y1-(r-1);j--){
				if ((temp-y1)% j==0){
					if (j-n>ans) ans=j-n;
				}
			}
		}
	}
	printf("%lld\n",ans);
	return 0;
}

#include <bits/stdc++.h>
using namespace std;

const long long N = 5e5;

int main(){
	long long n, l, r, k, rem, ans, cir, left, ll, rr, mid, maxx;
	cin >> n >> l >> r >> k;
	if (r >= l) rem = r - l + 1;
	else rem = r - l + 1 + n;
	ans = -1;
	for (long long i = min(n, N); i >= 0; i--){
		left = k % (n + i);
		if (left == 0) left = n + i;
		maxx = max(0LL, i - n + rem);
		if (left >= rem + max(0LL, maxx - 1) && left <= rem + min(rem, i)){
			ans = i;
			break;
		}
	}
	for (long long i = 0; i <= min(n, N); i++){
		ll = 0;
		rr = n + 1;
		while (rr - ll > 1){
			mid = (ll + rr) >> 1;
			maxx = max(0LL, mid - n + rem);
			if ((n + mid) * i + rem + max(0LL, maxx - 1) <= k) ll = mid;
			else rr = mid;
		}
		left = k % (n + ll);
		if (left == 0) left = n + ll;
		maxx = max(0LL, ll - n + rem);
		if (left >= rem + max(0LL, maxx - 1) && left <= rem + min(rem, ll)) ans = max(ans, ll);
	}
	cout << ans << '\n';
	return 0;
}

#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define pb push_back
#define x first
#define y second
#define fastread ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define PI (atan(1)*4)
#define mp make_pair
using namespace std;

ll xGCD(ll a, ll b, ll &x, ll &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }

    ll x1, y1, gcd = xGCD(b, a % b, x1, y1);
    x = y1;
    y = x1 - (a / b) * y1;
    return gcd;
}

ll n, l, r, k, val = -1, inlen, outlen;
int main()
{
    fastread;
    cin >> n >> l >> r >> k;
    inlen = (r - l + n) % n;
    outlen = n - inlen;
    inlen++;
    outlen--;
    ll num = k - inlen;
    ll a = num, b;
    if (a >= 0 && a <= inlen)
        val = max(val, a + outlen);
    a++;
    if (a >= 0 && a <= inlen)
        val = max(val, a + outlen);
    // cout << "chec" << val << endl;
    if (n <= 1e4) {
        // cout<<"haha"<<endl;
        for (int a = 0; a <= inlen; a++) {
            for (int b = 0; b <= outlen; b++) {
                ll den = inlen + a + b + outlen;
                ll num = k - inlen - a;
                if (num % den == 0 && num >= 0)
                    val = max(val, (ll)a + b);
                num++;
                if (num % den == 0 && num >= 0 && a != 0)
                    val = max(val, (ll)a + b);
            }
        }
        // cout << "haha" << val << endl;
    } else {
        // cout << "here" << endl;
        int lim = 1e7 + 2;
        for (int t = 1; t <= lim; t++) {
            ll rhs = k - inlen * (t + 1) - outlen * t;
            // if (t == 1)
            //     cout << inlen << " " << outlen << "  " << rhs << endl;
            if (rhs == 0)
                val = max(val, 0LL);
            else if (rhs > 0) {
                ll m = rhs / t;
                m = min(m, n);
                m = min(m, (rhs + outlen) / (t + 1));
                if (m >= ((rhs + t) / (t + 1)) && m <= n && m >= ((rhs - inlen + t - 1) / (t))) {
                    val = max(val, m);
                    // if (m == 19999)
                    // cout << "there" << t <<"  "<<rhs<<"   "<<inlen * (t + 1) + outlen * t<< endl;
                }
            }
            rhs++;
            if (rhs > 0) {
                ll m = rhs / t;
                // if (t == 1)
                //     cout << "vara" << m << endl;
                if (rhs % t == 0)
                    m--;
                m = min(m, n);
                m = min(m, (rhs + outlen) / (t + 1));
                // if (t == 1)
                //     cout << "vara" << m << endl;
                if (m >= (rhs + t) / (t + 1) && m <= n && m >= ((rhs - inlen + t - 1) / (t))) {
                    val = max(val, m);
                    // if (m ==19999)
                    // cout << "here" << t << " " << endl;
                }
            }
        }
    }
    cout << val;
    return 0;
}

#include <bits/stdc++.h>
#define ll long long
#define mst(a,x) memset(a,x,sizeof(a))
#define For(i, t) for(int i = 0; i < t; i++)
#define Debug(x) cerr << #x << " = "  << x << endl;
using namespace std;

ll x, y, n, l, r, k, ans;

void check(ll t) {
    ll L = max(max(k / (t + 1) + 1, n), (k - 2 * x + t - 1) / t);
    ll R = min(min((k - x) / t, 2*n), (2*n - 2*x + k + 1) / (t + 1));
    if(L <= R) ans = max(ans, R - n);
}

int main() {
    cin >> n >> l >> r >> k;
    x = (r - l + 1 + n) % n;
    // t == 0
    ans = -1;
    if(k <= 2 * x && k >= x) ans = min(x, k - x + 1) + n - x;
    if(x == 0 && k <= 2 * n && k >= n) ans = min(n, k - n + 1);

    for(ll i = 1; i <= k; i = k / (k / i) + 1)
        check(k / i);

    cout << ans << "\n";

	return 0;
}

#include<cstdio>
#include<algorithm>
#define int long long
using namespace std;
inline int read(){int x=0,f=1,ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-') f=-1; ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f;}
inline void write(int x){if (x<0) putchar('-'),x=-x; if (x>=10) write(x/10); putchar(x%10+'0');}
inline void writeln(int x){write(x); puts("");}
const int X=2e6+5;
int ans,n,l,r,k;
inline void init(){
	n=read(); l=read(); r=read(); k=read();
}
inline void solve(){
	int d=(r-l+n)%n+1; ans=-1;
	if (n<X) {
		for (int p=n;p>=0;p--){
			int y=(k-1)%(n+p)+1-d;
			if (y<0||y>p||y>d||d-(y+1)>n-p) continue;
			int y2=y+1;
			if (y2<=p&&y2<=d) ans=max(ans,p);
			if (d-y<=n-p) ans=max(ans,p);
		}
	}else{
		for (int i=0;i<=k/n;i++){
			int p=(k-2*d-(i-1)*n+1)/(i+1),y=k-i*(n+p)-d;
			if (y<0){
				if (!i) continue;
				int dis=(-y-1)/i+1;
				y+=i*dis; p-=dis;
			}
			if (p>n){
				y+=(p-n)*i; p==n;
			}
			if (y<0||y>p||y>d||d-(y+1)>n-p) continue;
			int y2=y+1;
			if (y2<=p&&y2<=d) ans=max(ans,p);
			if (d-y<=n-p) ans=max(ans,p);
		}
	}
	writeln(ans);
}
signed main(){
	init(); solve();
	return 0;
}

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <iostream>
#include <bitset>
using namespace std;
#define ll long long
ll n,k,l,r;
void ex_gcd(ll a,ll b,ll &x,ll &y)
{
	if(!b){x=1,y=0;return ;}
	ex_gcd(b,a%b,x,y);ll t=x;x=y;y=t-a/b*y;
}
int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	if(l>r)r=n-l+r+1,l=1;
	else r=r-l+1,l=1;
	if(n<=1000000)
	{
		ll ans=-1;
		for(int bit=1;bit<=2;bit++)for(int lt=1;lt<=bit;lt++)
		{
			for(int i=n+bit-1;i<=n*2;i++)
			{
				ll t=k/i;ll y=k%i;
				if(r==n)
				{
					if((y+lt-1)%i==0)ans=max(i-n,ans);
					continue;
				}
				// printf("%lld\n",y);
				if(i-n-(y-r+bit-lt)>n-r||y-r>i-n||y-r+1<lt||y>(r-1)*2+lt)continue;
				ans=max(i-n,ans);
			}
		}
		printf("%lld\n",ans);
	}else
	{
		ll lim=k/n,ans=-1;
		for(int bit=1;bit<=2;bit++)for(int lt=1;lt<=bit;lt++)
		{
			if(k<r+lt-1)continue;
			if(k<=r*2-2+lt){ans=max(ans,k-r+bit-1+n-r);continue;}
			for(int i=1;i<=lim;i++)
			{
				ll y=k/i;ll x=k%i;
				if(x<r-1+lt)
				{
					ll t=(r-2+lt-x)/i+1;
					x+=t*i;y-=t;
				}
				if((y-x+lt-bit)-2*(n-r)>0)
				{
					ll t=((y-x+lt-bit)-2*(n-r)-1)/(i+1)+1;
					x+=t*i;y-=t;
				}
				if(x>y)continue;
				if(r==n)
				{
					if((y-x-bit+lt)%(i+1)==0)
					{
						ll t=(y-x-bit+lt)/(i+1);
						x+=t*i;y-=t;
					}
					if((!x&&lt==bit)||x+bit-lt==y)ans=max(ans,y-n);
					continue;
				}
				if(y>2*(n-1)+bit||(y<n-1+bit&&y!=0))continue;
				if(x>(r-1)*2+lt||(x<r-1+lt&&x!=0))continue;
				ans=max(y-n,ans);
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return {i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
  ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
  *this << "[";
  for (c it = d.b; it != d.e; ++it)
    *this << ", " + 2 * (it == d.b) << *it;
  ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(x...) " [" #x ": " << (x) << "] "

using ll = long long;
using pll = pair <ll, ll>;

ll n, l, r, k;
ll d;
ll wynik = -1;
ll inf = 1e18;

void ans(ll S) {
	wynik = max(wynik, S);
}

void checkTriv(ll S) {
	if (S >= n && S <= 2 * n) {
		if (k % S == 0) ans(S - n);
		if (k % S == (S - 1) && S > n) ans(S - n);
	}
}

pll przetnij(pll a, pll b) {
	return {max(a.first, b.first), min(a.second, b.second)};
}
void checkInterval1(pll p, ll a, ll b) {
	p = przetnij(p, {-inf, (d - b) / a});
	p = przetnij(p, {-inf, (2 * d - 2 * n - b) / (a - 1)});
	p = przetnij(p, {(b - 2 * d - a - 1) / (-a), inf});
	p = przetnij(p, {(b + n - d - a) / (1 - a), inf});

	if (p.first <= p.second) ans(p.second - n);
}

void checkInterval2(pll p, ll a, ll b) {
	b++;
	p = przetnij(p, {-inf, (d + 1 - b) / a});
	p = przetnij(p, {-inf, (2 * d - 2 * n - b) / (a - 1)});
	p = przetnij(p, {(b - 2 * d - a - 1) / (-a), inf});
	p = przetnij(p, {(b + n - d - a) / (1 - a), inf});
	if (p.first <= p.second) ans(p.second - n);
}

void check(pll p, ll a, ll b) {
	checkInterval1(przetnij(p, {n, 2 * n}), a, b);
	checkInterval2(przetnij(p, {n, 2 * n}), a, b);
}

void check01(pll p, ll a) {
	if (a >= d && a <= 2 * d) {
		p = przetnij(p, {a + n - d, a + 2 * n - 2 * d});
		if (p.first <= p.second) ans(p.second - n);
	}
}

void check02(pll p, ll a) {
	a++;
	if (a >= d + 1 && a <= 2 * d) {
		p = przetnij(p, {a + n - d, a + 2 * n - 2 * d});
		if (p.first <= p.second) ans(p.second - n);
	}
}

int main() {
	cin >> n >> l >> r >> k;
	if (l <= r) d = r - l + 1;
	else d = n + 1 - (l - r);

	if (n == d) {
		for (ll x = 1; x * x <= k; ++x) {
			if (k % x == 0) {
				checkTriv(x);
				checkTriv(k / x);
			}
		}
		for (ll x = 1; x * x <= k + 1; ++x) {
			if ((k + 1) % x == 0) {
				checkTriv(x);
				checkTriv((k + 1) / x);
			}
		}
	}
	else {
		ll a = k;
		ll b = k;

		for(ll i = 2; i * i <= k; ++i)
		{
			b = k / i;
			ll a1 = k % a;
			ll an = k % (b + 1);

			if (a - b == 1) {
				check({a, a}, -1, (k % a) + a);
			}
			else {
				ll pa = (a1 - an) / (a - b - 1);
				ll pb = a1 - pa * a;
				check({b + 1, a}, pa, pb);
			}
			a = b;
		}

		for(ll i = b; i >= 1; --i) {
			check({i, i}, -1, (k % i) + i);
		}

		if (2 * n > k) {
			check01({k + 1, 2 * n}, k);
			check02({k + 1, 2 * n}, k);
		}
	}

	cout << wynik << endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll l,r,n,k,ans=-1;
int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	ll d=(r-l+n)%n+1;
	if(n<=2000000)
	{
		for(ll p=n;p>=0;p--)
		{
			ll y=(k-1)%(n+p)+1-d;
			if(y<0||y>p||y>d||d-(y+1)>n-p)continue;
			if((y+1<=p&&y+1<=d)||(d-y<=n-p))
			{
				ans=p;
				break;
			}
		}
	}
	else
	{
		for(ll i=0;i<=k/n;i++)
		{
			ll p=(k-2*d-(i-1)*n+1)/(i+1);
			ll y=k-i*(n+p)-d;
			if(y<0)
			{
				if(i==0)continue;
				ll dis=(-y-1)/i+1;
				y+=i*dis;
				p-=dis;
			}
			if(p>n)
			{
				y+=(p-n)*i;
//				n=p;
			}
			if(y<0||y>p||y>d||d-(y+1)>n-p)continue;
			if(y+1<=p&&y+1<=d)ans=max(ans,p);
			if(d-y<=n-p)ans=max(ans,p);
		}
	}
	printf("%lld\n",ans);
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define sqr(x) ((x)*(x))
#define mp make_pair
#define PI pair<ll,ll>
inline char gc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
#define gc getchar
inline ll read(){
	ll x = 0; char ch = gc(); bool positive = 1;
	for (; !isdigit(ch); ch = gc())	if (ch == '-')	positive = 0;
	for (; isdigit(ch); ch = gc())	x = x * 10 + ch - '0';
	return positive ? x : -x;
}
inline void write(ll a){
    if(a<0){
    	a=-a; putchar('-');
	}
    if(a>=10)write(a/10);
    putchar('0'+a%10);
}
inline void wri(ll a){write(a); putchar(' ');}
inline void writeln(ll a){write(a); puts("");}
const ll inf=1e18;;
ll n,l,r,k,t;
PI jiao(PI x,PI y){
	return mp(max(x.first,y.first),min(x.second,y.second));
}
inline ll chu(ll x,ll y){
	if(y==0)return -inf;
	return x%y==0?x/y:x/y+1;
}
void solve(ll l,ll r,int id){
	ll ans=-1;
	for(ll i=n,pos,jb,L,R;i<=2*n;i=pos+1){
		jb=k/i; pos=jb?k/jb:inf;
		if(id&2){
			L=chu(k-2*t,jb); if(jb==0&&k>2*t)L=inf;
			//k-i*jb<=2*t
		}else{
			L=chu(k-t+n,jb+1);
			//k-i*jb<=t+i-n
		}
		if(id&1){
			R=(k+2*n+1-2*t)/(jb+1); //k-i*jb>=2*t-1+(i-n) k-n*jb-i*jb>=2*t-1+i-n
		}else{
			R=jb?(k-t)/jb:inf; if(jb==0&&k<t)R=-inf;
			//k-i*jb>=t
		}
		PI T=jiao(jiao(mp(l+n,r+n),mp(L,R)),mp(i,pos));
		//if(l<=2&&r>=2)cout<<id<<" "<<T.first<<" "<<T.second<<" "<<k-jb*n+n+1-2*t<<" "<<jb<<" "<<i<<" "<<pos<<" "<<L<<" "<<R<<" "<<l<<" "<<r<<endl;
		if(T.first<=T.second)ans=max(ans,T.second);
	}
	if(ans>=0){
		cout<<ans-n<<endl; exit(0);
	}
}
signed main(){
	n=read(); l=read(); r=read(); k=read();
	t=(r-l+n)%n+1;
	if(t==n){
		ll ans=-1;
		for(ll i=1;i*i<=k;i++)if(k%i==0){
			if(i>=n&&i<=2*n)ans=max(ans,i-n);
			if(k/i>=n&&k/i<=2*n)ans=max(ans,k/i-n);
		}
		for(ll i=1;i*i<=k+1;i++)if((k+1)%i==0){
			if(i>n&&i<=2*n)ans=max(ans,i-n);
			if((k+1)/i>n&&(k+1)/i<=2*n)ans=max(ans,(k+1)/i-n);
		}
		cout<<ans<<endl; return 0;
	}
	if(t<=(n-(t-1))){
		solve(n-t+1,n,3);
		solve(t,n-t+1,2);
		solve(0,t,0);
	}else{
		solve(t,n,3);
		solve(n-t+1,t,1);
		solve(0,n-t+1,0);
	}
	puts("-1");
}
/*
	for(ll i=n;i>=0&&i>n-X;i--){
		ll zs=k%(n+i)?k%(n+i):n+i;// if(i==3)cout<<zs<<" "<<i-(n-(t-1))<<" "<<endl;
		if(zs>max((ll)0,i-(n-(t-1)))+t-1&&zs<=min(t,i)+t){
			cout<<i<<endl; return 0;
		}
	}
枚举i个人甜
t恰好吃完了k个
t<=k%(n+i)<=2*t
t n-(t-1)
n%(k+i)=n-(k+i)*jb
k-(n+i)*jb<=2*t
(n-k*jb-2*t)/jb<=i
k-(n+i)*jb<=t+i
(n-n*jb-t)/(jb+1)<=i
n-(n+i)*jb>2*t+i-n
t+i 2*t
t 2*t+(i-n))
*/

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <set>
#include <cmath>

using namespace std;
typedef long long ll;

ll N, K, L, R;
ll G, A;
ll ans;

void run (int use, ll ntot)
{
    if (N <= 5000)
    {

        for (int i = 0; i <= G; i++)
        {
            for (int j = 0; j <= A; j++)
            {
                // i before, j after
                ll rr = N + i + j + use;
                ll rv = (G + i) + (1 + use);
                if (ntot % rr == rv % rr)
                    ans = max (ans, (ll) i + j + use);
            }
        }
    }
    else
    {
        if (G + 1 + use <= ntot)
        {
            ll rv = ntot - G - 1 - use;
            if (rv <= G)
                ans = max (ans, rv + use + A);
        }

        for (int nrun = 1; nrun * N <= ntot; nrun++)
        {
            ll nstart = (nrun * (N + use)) + (G + 1 + use);
            // nrun+1 of before, nrun of after
            ll nleft = ntot - nstart;
            if (nleft >= 0)
            {
                ll nbefore = nleft % nrun;
                ll nafter = (nleft - ((nrun + 1) * (nbefore))) / nrun;
                if (nafter > A)
                {
                    ll ndrop = (nafter - A + nrun) / (nrun + 1);
                    nafter -= ndrop * (nrun + 1);
                    nbefore += ndrop * nrun;
                }
                if (nafter >= 0 && nafter <= A && nbefore >= 0 && nbefore <= G)
                    ans = max (ans, nbefore + nafter + use);
            }
        }
    }
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cin >> N >> L >> R >> K;

    G = (R - L + N) % N;
    A = (N - 1 - G);
    ans = -1;
    for (int i = 0; i <= 1; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            run (i, K + j);
        }
    }
    cout << ans << "\n";
}

#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string>
using namespace std;

int main(){
    long long n, l, r, k;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    long long res = 0;
    long long x = r-l+1;
    if(x <= 0) x += n;
    if(k < x){
        printf("-1\n");
        return 0;
    }
    if(n <= 10000){
        for(long long f=0; f<=n; f++){
            for(long long g=0; g<=min(x, f); g++){
                if(f-g > n-x) continue;
                if((k-x-g)%(n+f) == 0 && (k-x-g)/(n+f) >= 0) res = f;
                if(g >= 1 && (k-x-g+1)%(n+f) == 0 && (k-x-g+1)/(n+f) >= 0) res = f;
            }
        }
    } else{
        for(long long p=0; p<=k/n; p++){
            if(1){
                // g can be anything, must use all
                long long f = (n-x+k-p*n-x)/(1+p);
                long long g = k-p*n-x-p*f;
                if(g < 0) continue;
                if(g > x) continue;
                if(f*(p+1) < k-p*n-x) continue;
                res = max(res, f);
            }
            if(1){
                // g >= 1, the last person takes 1
                long long f = (n-x+k-p*n-x+1)/(1+p);
                long long g = k-p*n-x-p*f+1;
                if(g < 1) continue;
                if(g > x) continue;
                if(f*(p+1) < k-p*n-x) continue;
                res = max(res, f);
            }
        }
    }
    if(res) printf("%lld\n", res);
    else if((k-x)%n == 0) printf("0\n");
    else printf("-1\n");
    return 0;
}

#include<cstdio>
#define int long long
int n,m,l,r;
signed main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&m);
	r=(r-l+n)%n+1;
	if(m<r)return puts("-1"),0;
	if(n<=2e6){
		for(int i=n;i>=0;i--){
			int x=(m-1)%(n+i)+1-r;
			if(x<0||x>i||x>r||r-x-1>n-i)continue;
			if(x+1<=i&&x+1<=r)return printf("%d\n",i),0;
			if(r-x<=n-i)return printf("%d\n",i),0;
		}
	}
	else{
		for(int i=0;i<=m/n;i++){
			int x=(m-2*r-(i-1)*n+1)/(i+1);
			int y=m-i*(n+x)-r;
			if(y<0){
				if(i==0)continue;
				int dis=(-y-1)/i+1;
				y+=i*dis;
				x-=dis;
			}
			if(x>n)y+=(x-n)*i,x=n;
			if(y<0||y>x||y>r||r-y-1>n-x)continue;
			if(y+1<=x&&y+1<=r)return printf("%lld\n",x),0;
			if(r-y<=n-x)return printf("%lld\n",x),0;
		}

	}
	puts("-1");
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll n,l,r,m,s,up,x,y;

void exgcd(ll a,ll b,ll& x,ll &y) {
	if (!b) {x=1; y=0; return;}
	exgcd(b,a%b,y,x);
	y-=x*(a/b);
}

ll frac(ll x,ll y) {
	if (x>=0) return x/y;
	return x%y==0 ? x/y : x/y-1;
}

ll l1,r1,l2,r2,ans=-1;
int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&m);
	s=(r-l+n)%n+1; up=m-s;
	if (m<s) return puts("-1"),0;

	if (m-s<=s) ans=max(ans,m-s+n-s);
	for (ll i=n;i<=min(2*n,up);i=up/(up/i)+1) {
		ll k=up/i,right=up-k*n;
		if (right==0) {ans=max(ans,0ll); continue;}
		x=1; y=-1;
		x=x*right; y=y*right;
		l1=(x-s)%k==0 ? (x-s)/k : (x-s)/k+1;
		r1=x/k;
		//printf("%lld %lld\n",l1,r1);
		l2=y%(k+1)==0 ? -y/(k+1) : -y/(k+1)+1;
		r2=frac((n-s-y),(k+1));
		//printf("%lld %lld\n",l2,r2);
		if (l2>r1 || l1>r2 || l1>r1 || l2>r2) continue;
		//if (x+y+min(r1,r2)==75016001) printf("%lld %lld\n",min(r1,r2),k);
		ans=max(ans,x+y+min(r1,r2));
	}

	m++; up=m-s;
	if (m-s<=s) ans=max(ans,m-s+n-s);
	for (ll i=n;i<=min(2*n,up);i=up/(up/i)+1) {
		ll k=up/i,right=up-k*n;
		if (right==0) continue;
		x=1; y=-1;
		x=x*right; y=y*right;
		l1=(x-s)%k==0 ? (x-s)/k : (x-s)/k+1;
		r1=x%k==0 ? x/k-1 : x/k;
		l2=y%(k+1)==0 ? -y/(k+1) : -y/(k+1)+1;
		r2=frac((n-s-y),(k+1));
		if (l2>r1 || l1>r2 || l1>r1 || l2>r2) continue;
		//assert(y+(k+1)*min(r1,r2)<=n-s);
		/*if (x+y+min(r1,r2)==75016001) {
			printf("%lld %lld %lld %lld\n",l1,r1,l2,r2);
			printf("%lld %lld %lld %lld\n",r2,x-k*min(r1,r2),y+(k+1)*min(r1,r2),k);
		}*/
		ans=max(ans,x+y+min(r1,r2));
	}
	printf("%lld\n",ans);
	return 0;
}

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <queue>
#include <cmath>
#include <deque>
#include <algorithm>

using namespace std ;
typedef long long ll ;

ll n , k , l , r , a , b , res ;

ll le(ll x , ll y){
    if(x >= 0){
        return x / y ;
    } else {
        return -((-x + y - 1) / y) ;
    }
}

ll ge(ll x , ll y){
    if(x >= 0){
        return (x + y - 1) / y ;
    } else {
        return - ((-x) / y) ;
    }
}

int main(){

    scanf("%lld%lld%lld%lld",&n,&l,&r,&k) ;

    a = r - l + 1ll ;
    if(a <= 0)
        a += n ;
    b = n - a ;
    res = -1 * 1ll ;

    //O(N^2)
    if(n <= 2000 * 1ll){
        for(ll x = 0 ; x <= a ; ++ x){
            for(ll y = 0 ; y <= b ; ++y){
                ll kk = k - a - x ;
                ll tt = a + b + x + y ;
                if(kk % tt == 0){
                    res = max(res , x + y) ;
                }
                ++kk ;
                if(kk % tt == 0 && x > 0){
                    res = max(res , x + y) ;
                }
            }
        }
    } else {
        for(ll t = 0 ; t <= k / n ; ++t){
            if(t == 0){
                ll kk = k - a ;
                if(kk >= 0 && kk <= a){
                    res = max(res , kk + b) ;
                }
                ++kk ;
                if(kk >= 1 && kk <= a){
                    res = max(res , kk + b) ;
                }
                continue ;
            }
            ll kk = k - a * (t + 1ll) - b * t ;
            ll maxs = min(le(a - kk , t) , le(-kk , t + 1)) ;
            ll mins = max(ge(-kk , t) , ge(-kk - b , t + 1)) ;
            if(mins <= maxs){
                res = max(res , -mins) ;
            }
            ++kk ;
            maxs = min(le(a - kk , t) , le(-kk , t + 1)) ;
            mins = max(ge(1 - kk , t) , ge(-kk - b , t + 1)) ;
            if(mins <= maxs){
                res = max(res , -mins) ;
            }
        }
    }

    printf("%lld\n",res) ;

    return 0 ;

}

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

const ll SQ = 1e6;

ll N, L, R, K, D, ans = -1;

void solve(ll t, ll K) {
    if(N > SQ) {
        for(ll i = 0; i <= SQ; i++) {
            if(N * i + D > K) break;

            ll R = K - N * i - D;

            ll s = t, e = N, p = -1;
            while(s <= e) {
                ll m = (s + e)>>1;

                ll le = m * i + max(t, m - N + D);
                ll ri = m * i + min(D, m);
                if(ri < R) {
                    s = m + 1;
                    continue;
                }
                if(R < le) {
                    e = m - 1;
                    continue;
                }
                p = m;
                s = m + 1;
            }
            if(p != -1) {
                ans = max(ans, p);
            }
        }
        return;
    }

    if(K - D < 0) return;

    for(ll i = t; i <= N; i++) {
        ll R = K - D;
        ll rem = R % (N + i);

        ll le = max(t, i - N + D);
        ll ri = min(D, i);

        if(le <= rem && rem <= ri) {
            ans = max(ans, i);
        }
    }
}

int main() {
    cin >> N >> L >> R >> K;

    D = (R + N - L) % N + 1;

    solve(0, K);
    solve(1, K + 1);

    cout << ans;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define LL long long
ll B;
ll n;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)
	{
		x=1;y=0;return a;
	}
	ll e=exgcd(b,a%b,x,y);
	ll kkz=x;x=y;y=kkz-a/b*y;
	return e;
}
ll ceildiv(ll a,ll b){
    if(a%b==0)return a/b;
    else return a/b+1;
}
ll cal(ll a,ll x, ll y,bool flag){
    ll t=0;
    if(a!=0){
        ll L=max(ceildiv(y-B,a),ceildiv(y-x,a+1))   ;
        ll R=min(flag?y-1:y,(n-B+y-x)/(a+1));
        if(L>R)return -1;
        t=R;
        x+=t;
    }
    else{
        if(y>B)return -1;
        x=min(n,n-B+y);
    }
    return x;
}

ll GetX(ll a,ll b,ll c,bool flag=1){
    //ax+by=c
    if(c<0)return -1;
    ll x,y;
    ll k=exgcd(a,b,x,y);
    if(c%k)return -1;
    k=c/k;
    x*=k;y*=k;
    ll x1=cal(a,x,y,flag);
    return x1;
}
bool can(ll x,ll y,ll k){
    if(y>=0&&y<=B&&y<=x&&x<=n-B+y);
    else return 0;
    if((k-B-y)%(n+x)==0)return 1;
    if(y>0&&(k-B-(y-1))%(n+x)==0)return 1;
    return 0;
}
int main()
{
    ll k,l,r;
    cin>>n>>l>>r>>k;
    ll b=r>=l?r-l+1:n-(l-r-1);
    ll c;
    ll lc=(k-b-n)/(2*n);
    ll rc=(k-b)/n;
    ll ans=-1;
    B=b;
    //cout<<(ll)pow(k,0.33333)<<endl;
    if(n>pow((double)k,1.0/3))
        for(c=lc;c<=rc;++c){
            ll x=max(GetX(c,1,k+1-b-c*n,1),GetX(c,1,k-b-c*n));
            ans=max(ans,x);
        }
    else{
        for(ll i=0;i<=n;++i)
            for(ll j=0;j<=i;++j){
                bool f;
                    if(f=can(i,j,k))ans=max(ans,i);
        }
    }
    cout<<ans<<endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;

#define ll long long

ll ple(ll fz, ll fm)
{
    return fz / fm;
}

ll pge(ll fz, ll fm)
{
    return (fz + fm - 1) / fm;
}

ll le (ll fz, ll fm)
{
    return fz >= 0 ? ple(fz, fm) : -pge(-fz, fm);
}

ll ge(ll fz, ll fm)
{
    return fz >= 0 ? pge(fz, fm) : -ple(-fz, fm);
}

int main()
{
	ll	n, k, l, r;
	scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
	r = r - l + 1;
	if(r <= 0)
		r += n;
	if(n <= k / n)
	{
		r %= n;
		for(ll i = n; ~i; i--)
		{
			ll	res = k % (n + i) - r;
			if(res >= 0 && res <= r && res <= i && min(res + 1, r) >= i - (n - r))
				return printf("%lld\n", i), 0;
		}
		puts("-1");
	}
	else
	{
		ll	ans = -1;
		if(k >= r && k <= r * 2)
			ans = max(ans, min(k - r + 1, r) + n - r);
		for(ll i = 1; i <= k / n; i++)
		{
			ll	a0 = k - n * i - r;
			ll	l0 = max(ge(a0 - r, i), ge(a0, i + 1));
			ll	r0 = min(le(a0, i), le(a0 + n - r, i + 1));
			if(l0 <= r0)
				ans = max(ans, r0);
			++a0;
			l0 = max(ge(a0 - r, i), ge(a0, i + 1));
			r0 = min(le(a0 - 1, i), le(a0 + n - r, i + 1));
			if(l0 <= r0)
				ans = max(ans, r0);
		}
		printf("%lld\n", ans);
	}
	return 0;
}

#include <cstdio>
#include <algorithm>
using namespace std;

#ifdef LOCAL
#define LL "%lld"
#else
#define LL "%I64d"
#endif
typedef long long ll;
ll n, l, r, L, k, last;

ll solveSum(ll x) {
	ll l = last, r = k;
	ll maxIn = min(x - last, n - L);
	ll minOut = x - maxIn;
	ll maxOut = min(x, L);
	while (l <= r) {
		ll mid = (l + r) / 2;
		ll lb = mid * (n + x) + L + minOut;
		ll rb = mid * (n + x) + L + maxOut;
		if (lb > k) {
			r = mid - 1;
		} else if (rb < k) {
			l = mid + 1;
		} else {
			return x;
		}
	}
	return -1;
}

ll solveTimes(ll x) {
	ll l = last, r = n, ans = -1;
	while (l <= r) {
		ll mid = (l + r) / 2;
		ll in = mid;
		ll out = min(mid, n - L);
		in -= out;
		if (in < last) in++, out--;
		ll lb = x * (n + mid) + L + in;
		in = min(mid, L);
		out = mid - in;
		ll rb = x * (n + mid) + L + in;
		if (lb > k) {
			r = mid - 1;
		} else if (rb < k) {
			l = mid + 1;
		} else {
			l = mid + 1;
			ans = max(ans, mid);
		}
	}
	return ans;
}

int main() {
	scanf(LL LL LL LL, &n, &l, &r, &k);
	l--, L = (r - l + n) % n;
	ll ans = -1;
	for (ll i = 0; i * i <= k; i++) {
		ans = max(ans, solveSum(i));
		ans = max(ans, solveTimes(i));
	}
	if (L > 0) {
		last = 1;
	}
	k++;
	for (ll i = 0; i * i <= k; i++) {
		ans = max(ans, solveSum(i));
		ans = max(ans, solveTimes(i));
	}
	printf(LL "\n", ans);
	return 0;
}

#include<bits/stdc++.h>
using namespace std;

#define ll long long
namespace exgcd{
  ll gao(ll a,ll b,ll &x,ll &y){
    if (b==0){
      x=1; y=0; return a;
    }
    ll k=gao(b,a%b,x,y);
    ll t=x; x=y; y=t-a/b*y;
    return k;
  }
  bool fuck(ll a,ll b,ll c,ll lx,ll ly,ll &x,ll &y){
    ll g=gao(a,b,x,y);
    if (c%g) assert(0);
    a/=g; b/=g; c/=g;
    x*=c; y*=c;
    x=x%b-b-b+lx/b*b;
    while (x+b<=lx) x+=b; if (x<0) return 0;
    y=(c-a*x)/b;
    if (y>=0&&y<=ly) return 1;
    if (y>ly) return 0;
    ll d=(abs(y)+a-1)/a;
    y+=d*a; x-=d*b;
    return x>=0&&x<=lx&&y>=0&&y<=ly;
  }
}

ll n, d, k, x, y, ans=-1;

void doit(ll t){
  if (t<0) return;
  if (t==0){
    if (k>=d&&k<=2*d){
      ans=max(ans,(k-d==d? d: k-d+1)+n-d);
    }
    return;
  }
  ll aim=k-t*n-d;
  if (exgcd::fuck(t,t+1,aim,n-d,d,x,y)){
    ans=max(ans,x+y);
  }
}

void doit2(ll t){
  if (t<=0) return;
  ll aim=k-t*n-d;
  if (exgcd::fuck(t,t+1,aim,n-d,d,x,y)){
    if (!y) x-=t+1, y+=t;
    if (x>=0&&x<=n-d&&y>=0&&y<=d){
      ans=max(ans,x+y);
    }
  }
}

int main(){
  cin>>n>>x>>y>>k;
  d= y>=x? y-x+1: y+n-x+1;
  doit(0);
  for (ll i=n, nex;i<=n*2;i=nex+1){
    ll t=k/i; nex= t==0? 1e18: k/t;
    doit(t-1); doit(t); doit(t+1);
  }
  ++k;
  for (ll i=n, nex;i<=n*2;i=nex+1){
    ll t=k/i; nex= t==0? 1e18: k/t;
    doit2(t-1); doit2(t); doit2(t+1);
  }
  cout<<ans<<endl;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

ll n, k, l, r, t;
ll extgcd(ll a, ll b, ll c, ll &x, ll &y){
	if(b == 0){
		x = c / a, y = 0;
		return a;
	}
	ll g = extgcd(b, a % b, c, y, x);
	y -= x * (a / b);
	return g;
}
bool getans(ll a, ll b, ll c, ll &x, ll &y, ll n){
	if(a == 0){y = c / b; x = n; return y >= 0 && y <= t;}
	extgcd(a, b, c, x, y);
	y = (y % a + a) % a;
	if(y > t) return false;
	x = (c - y * b) / a;
	if(x > n) y += (x - n) * a, x = n;
	if(x < 0 || x > n || y < 0 || y > t) return false;
	return true;
}
int main(){
	scanf("%lld%lld%lld%lld", &n, &l, &r, &k), --l, --r;
	t = (r + n - l) % n + 1;
	if(k / n > n){
		for(ll x = n; x >= 0; x--){
			ll a, b;
			if(getans(x + n, 1, k - t, a, b, k / n) && x - b <= n - t)
				return printf("%lld\n", x) * 0;
			if(getans(x + n, 1, k + 1 - t, a, b, k / n) && x - b <= n - t && b > 0)
				return printf("%lld\n", x) * 0;
		}
		puts("-1");
	} else {
		ll res = -1;
		for(ll w = 0; w * n + t <= k; w++){
			ll a, b;
			if(getans(w, 1, k - n * w - t, a, b, n)){
				ll kk = a - b <= n - t ? 0 : (n - t - a + b - w) / (w + 1);
				a += kk, b -= kk * w;
				if(a >= 0 && a <= n && b >= 0 && b <= t) res = max(res, a);
			}
			if(getans(w, 1, k + 1 - n * w - t, a, b, n)){
				ll kk = a - b <= n - t ? 0 : (n - t - a + b - w) / (w + 1);
				a += kk, b -= kk * w;
				if(b <= 0) b += w, --a;
				if(a >= 0 && a <= n && b >= 0 && b <= t) res = max(res, a);
			}
		}
		printf("%lld\n", res);
	}
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define F first
#define S second
typedef long long   ll;
typedef long double ld;
typedef pair <ll, ll> pll;

ifstream in;
ofstream out;

const long long kk=1000;
const long long ml=kk*kk;
const long long mod=ml*kk+7;
const long long inf=ml*ml*ml+7;
const long long con=15*ml;
const long long scon=5*kk;

ll n,k,l,r,i,j,ans,kol;
vector <ll> m;
bool viv=false;

void work(ll x)
{
if (x<0||x>n)
  return;
ll lk=k;
lk%=(n+x);
if (lk==0)
  lk=n+x;
if (lk<kol)
  return;
if (lk>kol*2)
  return;
if (lk==kol*2)
  lk--;
ll slad=(n-kol)+(lk-kol+1);
if (slad>=x)
  ans=max(ans, x);
}

int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin>>n>>l>>r>>k;
kol=(r+n+1-l)%n;
if (kol==0)
  kol=n;

ans=-1;
for (i=0; i<con; i++)
  work(n-i);
if (ans!=-1)
  {cout<<ans; return 0;}
for (i=0; i<con; i++)
  work(i);

for (i=0; i<ml/10; i++)
  {
  ll x;
 /*
  ll lk=k-((n+x)*i);
  lk=kol+(x-n+kol);
  2*kol+x-n=k-i*n-i*x;
  x*(i+1)=k-i*n-2*kol+n;
// */
  x=(n+k-i*n-2*kol)/(i+1);
  for (ll j=-10; j<10; j++)
    work(x+j);
  }

cout<<ans;

    return 0;
}

// I love meowmur
// We miss you, Arthur
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast", "unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>

#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define all(a) (a).begin(), (a).end()
#define sz(a) (ll)((a).size())
#define heap priority_queue
#define hash_map unordered_map
#define hash_set unordered_set
#define ft first
#define sd second
#define fast ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define endl "\n"
#define mineq(a, b) (a) = ((a)>(b))?(b):(a)
#define maxeq(a, b) (a) = ((a)<(b))?(b):(a)
#define die(cond) if (cond) for (;;){}
#define y1 y_1
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
typedef vector<ll> vll;
typedef set<ll> sll;
typedef map<ll, ll> mll;
const ll inf = numeric_limits<ll>::max() / 2;
const ld eps = 1e-9;
const ld pi = acos(-1);

inline void solve(), read();

int main() {
	fast;
	read();
	solve();
	return 0;
}

ll gcd(ll a, ll b) {
	while (b != 0) {
		a %= b;
		swap(a, b);
	}
	return a;
}
pll exgcd(ll a, ll b) {
	if (a == 0) {
		return { 0, 1 };
	}
	ll x0, y0;
	tie(x0, y0) = exgcd(b % a, a);
	ll x = y0 - b / a * x0;
	ll y = x0;
	return { x, y };
}

ll n, l, r, k;
ll x, y;

pll solve(ll a, ll b, ll c) {
	ll x, y;
	tie(x, y) = exgcd(a, b);
	ll g = gcd(a, b);
	if (c % g != 0) {
		return { -inf, -inf };
	}
	c /= g;
	x *= c, y *= c;
	return { x, y };
}

ll n2(ll f) {
	if (f) {
		++k;
	}
	ll ans = -1;
	for (ll a = f; a <= x; a++) {
		for (ll b = 0; b <= y; b++) {
			if (k - x - a < 0 || (k - x - a) % (x + y + a + b) != 0) {
				continue;
			}
			maxeq(ans, a + b);
		}
	}
	return ans;
}
ll nk(ll f) {
	if (f) {
		++k;
	}
	ll ans = -1;
	if (k - x <= x) {
		maxeq(ans, k - x + y);
	}
	for (ll t = 1; t <= k / n; t++) {
		ll c = k - t * n - x;
		if (c < 0) {
			continue;
		}
		ll a, b;
		tie(a, b) = solve(t + 1, t, c);
		if (a == -inf) {
			continue;
		}
		a = (a % t + t) % t;
		b = (c - a * (t + 1)) / t;
		if (b > y) {
			ll diff = b - y;
			ll ch = (diff + t) / (t + 1);
			b -= ch * (t + 1);
			a += ch * t;
		}
		if (f && !a) {
			continue;
		}
		if (0 <= a && a <= x && 0 <= b && b <= y) {
			maxeq(ans, a + b);
		}
	}
	return ans;
}

inline void solve() {
	x = (r - l + n) % n + 1;
	y = n - x;
	if (k < x) {
		cout << -1 << endl;
		return;
	}
	ll ansk = -1, ansk1 = -1;
	if (n <= 1e4) {
		ansk = n2(0);
		ansk1 = n2(1);
	} else {
		ansk = nk(0);
		ansk1 = nk(1);
	}
	ll ans = max(ansk, ansk1);
	cout << ans << endl;
}

inline void read() {
	cin >> n >> l >> r >> k;
}

#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define rep(i, a, b) for(int i=(a); i<(b); i++)
#define per(i, a, b) for(int i=(b)-1; i>=(a); i--)
#define sz(a) (int)a.size()
#define de(a) cout << #a << " = " << a << endl
#define dd(a) cout << #a << " = " << a << " "
#define all(a) a.begin(), a.end()
#define pw(x) (1ll<<(x))
#define endl "\n"
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
ll n, l, r, k;

bool checks(ll s)
{
	ll x = (k-r+l-1)/(n+s);
	ll sp = k-r+l-1 - x*(n+s);
	if(sp < r-l+1)
		sp++;
	if(sp > r-l+1)
	{
		return false;
	}
	if(s-sp > n-r+l-1)
	{
		return false;
	}
	return true;
}

int main()
{
	ios_base::sync_with_stdio(0);
	cin >> n >> l >> r >> k;
	if(l > r) r+=n;
	if(k < r-l+1)
	{
		cout << "-1";
		return 0;
	}
	if(n < 1e6)
	{
		ll res=-1;
		ll s=0, sp=0;
		for(s=0; s <= n; s++)
		{
			if(checks(s))
				res = s;
		}
		cout << res << "\n";
	}
	else
	{
		ll res = -1;
		ll m = k-r+l-1;
		for(ll x=1; x < 1e6; x++)
		{
			ll a, b;
			a = (m-x*n-r+l-1)/x;
			b = (m-x*n+n-r+l)/(x+1);
			b = min(b, n);
			if(a <= b && checks(b))
				res = max(res, b);
			else if(a+1 <= b && checks(b-1))
				res = max(res, b-1);
		}
		ll sp = k-r+l-1;
		if(sp < r-l+1)
			sp++;
		if(sp >= 0 && sp <= r-l+1)
		{
			res = max(res, n-r+l-1+sp);
		}
		cout << res << "\n";
	}
	return 0;
}

#include<bits/stdc++.h>

typedef long long ll;

ll divide(ll a, ll b){
    return a / b - ((a ^ b) < 0 && a % b);
}

ll solvele(ll a, ll b){
    return divide(b, a);
}

ll solvege(ll a, ll b){
    return divide(b + a - 1, a);
}

int main(){
    ll n, l, r, k;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    ll x = r - l + 1;
    if (x < 0){
        x += n;
    }
    if (x == n){
        ll max = -1;
        for (ll i = 1; i * i <= k; ++ i){
            if (k % i == 0){
                if (i <= n << 1){
                    max = std::max(max, i - n);
                }
                if (k / i <= n << 1){
                    max = std::max(max, k / i - n);
                }
            }
            if ((k + 1) % i == 0){
                if (n + 1 <= i && i <= n << 1){
                    max = std::max(max, i - n);
                }
                if (n + 1 <= k / i && k / i <= n << 1){
                    max = std::max(max, k / i - n);
                }
            }
        }
        printf("%lld\n", max);
        return 0;
    }
    ll ans = -1;
    for (ll i = 1, j; i <= k; i = j + 1){
        ll t = k / i;
        j = k / t;
        ll min = std::max(0ll, i - n), max = j - n;
        max = std::min(max, solvele(t, k - t * n - x));
        min = std::max(min, solvege(t, k - t * n - 2 * x));
        max = std::min(max, solvele(t + 1, k - t * n - x + n - x));
        min = std::max(min, solvege(t + 1, k - t * n - x));
        if (min <= max){
            ans = std::max(ans, max);
        }
        min = std::max(0ll, i - n), max = j - n;
        max = std::min(max, solvele(t, k - t * n - x));
        min = std::max(min, solvege(t, k - t * n - 2 * x + 1));
        max = std::min(max, solvele(t + 1, k - t * n - x + n - x + 1));
        min = std::max(min, solvege(t + 1, k - t * n - x + 1));
        if (min <= max){
            ans = std::max(ans, max);
        }
    }
    ll min = std::max(0ll, k - n + 1), max = n;
    if (0 <= k - x && k - x <= x){
        max = std::min(max, solvele(1, k - x + n - x));
        min = std::max(min, solvege(1, k - x));
        if (min <= max){
            ans = std::max(ans, max);
        }
    }
    min = std::max(0ll, k - n + 1), max = n;
    if (1 <= k - x + 1 && k - x + 1 <= x){
        max = std::min(max, solvele(1, k - x + n - x));
        min = std::max(min, solvege(1, k - x + 1));
        if (min <= max){
            ans = std::max(ans, max);
        }
    }
    printf("%lld\n", ans);
    return 0;
}

#include <cstdio>
#include <algorithm>

typedef long long ll;
ll n, k, l, r;

int main() {
	scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
	ll m = r - l + 1;
	if(m <= 0) m += n;
	ll ans = -1;
	if((double)n * n <= 1e7) {
		for(ll a = 0; a <= m; a++) for(ll b = 0; b <= n - m; b++) {
			ll kk = k - m - a;
			ll nn = n + a + b;
			if(kk >= 0 && kk % nn == 0) ans = std::max(ans, a + b);
			if(a >= 1) {
				kk++;
				if(kk >= 0 && kk % nn == 0) ans = std::max(ans, a + b);
			}
		}
	}
	else {
		for(ll t = 1; t * n <= k - m; t++) {
			ll cur = k - m - n * t;
			ll y = std::min(cur / t, n);
			ll x = cur - t * y;
			if(x <= y && x <= m) ans = std::max(ans, y);

			cur++;
			y = std::min(cur / t, n);
			x = cur - t * y;
			if(x == 0) {
				y--;
				x += t;
			}
			if(x <= y && x <= m) ans = std::max(ans, y);
		}
		ll a = k - m;
		if(1 <= a && a <= m) ans = std::max(ans, a);
		a++;
		if(1 <= a && a <= m) ans = std::max(ans, a);
	}
	printf("%lld\n", ans);
	return 0;
}

//jinhaonan
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
inline ll read(){
	ll x=0;char c=getchar();bool f=0;
	for(;c>'9'||c<'0';f=c=='-',c=getchar());
	for(;c>='0'&&c<='9';x=(x<<1)+(x<<3)+c-'0',c=getchar());
	return f?-x:x;
}
inline void write(ll x){
	if(x<0)putchar('-'),x=-x;
	if(x>=10)write(x/10);
	putchar(x%10+48);
}
template<class T>bool Enlarge(T &a,T const &b){
	return a<b?a=b,1:0;
}
template<class T>bool Reduce(T &a,T const &b){
	return a>b?a=b,1:0;
}
ll n,l,r,k,m;
void work1(){
	ll x=n-m;
	for(ll i=2*n;i>=n;--i){
		ll t=(k-1)%i+1;
		if(m<=t&&t<=m*2)
			if((t-x<=i&&i<=2*x+t)||((t+1-x<=i&&i<=2*x+t+1))){
				write(i-n);puts("");
				return;
			}
	}
	puts("-1");
}
void work2(){
	ll res=-n,x=n-m;
	if(m<=k&&k<=2*m){
		write(min(k-m+1+x,n));puts("");
		return;
	}
	for(ll i=1,lim=k/n;i<=lim;++i){
		ll L=(k-2*m+i-1)/i,R=(k-m)/i;
		Enlarge(L,n);Reduce(R,2*n);
		Enlarge(L,(k-x+i)/(i+1));Reduce(R,(2*x+k+1)/(i+1));
		if(L<=R)Enlarge(res,R);
	}
	write(res<0?-1:res-n),puts("");
}
int main(){
	n=read(),l=read(),r=read(),k=read();
	m=r-l+1;
	if(m<0)m+=n;
	if(n<=k/n)work1();else work2();
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXSIZE=10000020;
int bufpos;
char buf[MAXSIZE];
#define NEG 0
void init(){
	#ifdef LOCAL
		freopen("1063D.txt","r",stdin);
	#endif
	buf[fread(buf,1,MAXSIZE,stdin)]='\0';
	bufpos=0;
}
#if NEG
ll readint(){
	bool isneg;
	ll val=0;
	for(;!isdigit(buf[bufpos]) && buf[bufpos]!='-';bufpos++);
	bufpos+=(isneg=buf[bufpos]=='-');
	for(;isdigit(buf[bufpos]);bufpos++)
		val=val*10+buf[bufpos]-'0';
	return isneg?-val:val;
}
#else
ll readint(){
	ll val=0;
	for(;!isdigit(buf[bufpos]);bufpos++);
	for(;isdigit(buf[bufpos]);bufpos++)
		val=val*10+buf[bufpos]-'0';
	return val;
}
#endif
char readchar(){
	for(;isspace(buf[bufpos]);bufpos++);
	return buf[bufpos++];
}
int readstr(char* s){
	int cur=0;
	for(;isspace(buf[bufpos]);bufpos++);
	for(;!isspace(buf[bufpos]);bufpos++)
		s[cur++]=buf[bufpos];
	s[cur]='\0';
	return cur;
}
//x<=k mod (n+a)<=x+a
int main(){
	init();
	ll n=readint(),l=readint(),r=readint(),k=readint();
	ll x=(r-l+1+n)%n;
	if (k<x)
		return puts("-1"),0;
	ll ans=-1;
	if (k<=2*x)
		return printf("%lld",n),0;
	for(ll i=1,nxt;i<=k;i=nxt+1){
		ll w=k/i;
		nxt=k/w;//[i,nxt];
		// printf("%lld to %lld\n",i,nxt);
		//case 1:[n,n+x]
		ll l=max(i,n),r=min(nxt,n+x);
		if (l<=r){
			//k-wa in [x,x+a-n]
			//a<=(k-x)/w a>=(k-x+n)/(w+1)
			ll l1=max((k-x+n-1)/(w+1)+1,l),r1=min((k-x)/w,r);
			if (l1<=r1)
				ans=max(ans,r1-n);
		}
		l=max(i,n+x),r=min(nxt,2*n);
		//case 2:[n+x,2*n]
		if (l<=r){
			//k-wa in [x,2*x] k-wa<=2*x k-2*x<=wa a>=(k-2*x)/w
			ll l1=max((k-2*x-1)/w+1,l),r1=min((k-x)/w,r);
			if (l1<=r1)
				ans=max(ans,r1-n);
		}
	}
	printf("%lld",ans);
}

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

long long N, K, L, R, S, maxn = -1;

int main() {
	cin >> N >> L >> R >> K;
	S = (R - L + 1 + N) % N;

	// 1 周以上の場合
	long long B = K / (2LL * N); if (B == 0) B = 1;
	vector<long long>E;
	for (long long i = 2LL * N; i >= 2LL * N - 2000; i--) {
		if (i < N) break;
		for (long long j = 0; j <= 3; j++) E.push_back(K / i + j);
		for (long long j = 0; j <= 3; j++) E.push_back((K + 1) / i + j);
	}
	sort(E.begin(), E.end());
	E.erase(unique(E.begin(), E.end()), E.end());

	for (long long i : E) {
		if (i == 0) continue;
		long long BASE = (1LL * i + 1LL) * S + (1LL * i) * (N - S);
		if (K < BASE) continue;

		long long UPLIMIT_1 = N - S;
		long long UPLIMIT_2 = S;
		long long SA1 = K - BASE;
		long long V1 = SA1 / i;
		long long V2 = SA1 % i; V1 -= V2;
		long long SABUN = V1 - UPLIMIT_1;
		if (SABUN >= 0) { long long P = (SABUN + i) / (i + 1); V1 -= 1LL * (i + 1)*P; V2 += 1LL * i*P; }

		if (V1 < 0 || V2 < 0 || V1 > UPLIMIT_1 || V2 > UPLIMIT_2) continue;

		long long sum = V1 + V2;
		maxn = max(maxn, sum);
	}

	// 1 周以上で合計が K + 1 以上の場合
	for (long long i : E) {
		if (i == 0) continue;
		long long BASE = (1LL * i + 1LL) * S + (1LL * i) * (N - S);
		if (K + 1 < BASE) continue;

		long long UPLIMIT_1 = N - S;
		long long UPLIMIT_2 = S;
		long long SA1 = K + 1 - BASE;
		long long V1 = SA1 / i;
		long long V2 = SA1 % i; V1 -= V2;
		long long SABUN = V1 - UPLIMIT_1;
		if (SABUN >= 0) { long long P = (SABUN + i) / (i + 1); V1 -= 1LL * (i + 1)*P; V2 += 1LL * i*P; }
		if (V2 == 0) { V2 += i; V1 -= (i + 1); }

		if (V1 < 0 || V2 < 0 || V1 > UPLIMIT_1 || V2 > UPLIMIT_2) continue;

		long long sum = V1 + V2;
		maxn = max(maxn, sum);
	}

	// 0 周の場合
	if (true) {
		if (K == S) maxn = max(maxn, 1LL + (N - S));
		else if (K > S && K <= 2LL * S) maxn = max(maxn, min(S, K - S + 1) + (N - S));
	}
	cout << maxn << endl;
	return 0;
}

#include <iostream>
#include <fstream>
using namespace std;

long long bs(long long t,long long l,long long r,long long h,long long x,long long n)
{
    long long mid,tp=-1;
    while (l<=r)
    {
        mid=(l+r)/2;
        if (mid<(t-mid*x)) l=mid+1; else
        if (mid-(t-mid*x)<=n-h && (t-mid*x)<=h)
        {
            l=mid+1;
            tp=mid;
        } else r=mid-1;
    }
    return tp;
}

int main()
{
    //freopen("m.inp","r",stdin);
    //freopen("m.out","w",stdout);
    long long n,l,r,k,h,t,m2=-1;
    cin>>n>>l>>r>>k;
    if (r>=l) h=r-l+1; else h=n-l+1+r;
    if (n<=1000000)
    {
        for (int m=n;m>=1;m--)
        {
            t=k%(n+m);
            if ((t>=max(h,m-n+2*h) && t<=min(m+h,2*h)) || (t==0 && ((l==1 && r==n) || (l-1==r))))
            {
                m2=m;
                break;
            }
        }
        k=k+1;
        for (int m=n;m>=1;m--)
        {
            t=k%(n+m);
            if ((t>=max(h,m-n+2*h) && t<=min(m+h,2*h)) || (t==0 && ((l==1 && r==n) || (l-1==r))))
            {
                if (m>m2) m2=m;
                break;
            }
        }
        cout<<m2;
    }
    else
    {
        long long m3;
        if (k<=2*h) m2=k-h+(n-h);
        for (int i=1;i<=k/n;i++)
        {
            t=k-n*i-h;
            m3=bs(t,0,n,h,i,n);
            if (m3!=-1)
            {
                if (m3>m2) m2=m3;
                break;
            }
        }
        k=k+1;
        if (k<=2*h) m2=k-h+(n-h);
        for (int i=1;i<=k/n;i++)
        {
            t=k-n*i-h;
            m3=bs(t,0,n,h,i,n);
            if (m3!=-1)
            {
                if (m3>m2) m2=m3;
                break;
            }
        }
        cout<<m2;
    }
    return 0;
}

#include <algorithm>
#include <iostream>

#include <cmath>

using namespace std;

typedef long long ll;

int main(int argc, char *argv[]) {
#ifdef KANARI
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ll n, l, r, k;
	cin >> n >> l >> r >> k;
    ll first = (r - l + n) % n + 1;
    k -= first;
    ll threshold = static_cast<ll>(sqrt(k));
    ll max_t = (k + 1) / n;

    ll ans = -1LL;
    if (max_t < threshold) {
        // check for t = 0
        {
            ll min_s = k;
            if (min_s <= first) ans = max(ans, n - max(0LL, first - min_s - 1));
        }
        for (ll t = 1; t <= max_t; ++t) {
            ll rem = k - t * n;
            ll s = rem / t;
            ll min_s1 = rem % t;
            if (min_s1 <= s && min_s1 <= first && (s - min_s1) <= (n - first)) {
                ans = max(ans, s);
            } else {
                rem = (k + 1) - t * n;
                s = rem / t;
                min_s1 = rem % t;
                if (min_s1 > 0 && min_s1 <= s && min_s1 <= first && (s - min_s1) <= (n - first))
                    ans = max(ans, s);
            }
        }
    } else {
        // n <= threshold
        for (ll s = 0; s <= n; ++s) {
            ll min_s1 = k % (s + n);
            if (min_s1 <= s && min_s1 <= first && (s - min_s1) <= (n - first)) {
                ans = max(ans, s);
            } else {
                min_s1 = (k + 1) % (s + n);
                if (min_s1 > 0 && min_s1 <= s && min_s1 <= first && (s - min_s1) <= (n - first))
                    ans = max(ans, s);
            }
        }
    }

    cout << ans << endl;

	fclose(stdin);
	fclose(stdout);
	return 0;
}

#pragma region
#include <bits/stdc++.h>
using namespace std;
#define ri register int
#define il inline
#define LL long long
#define uint unsigned int
#define ull unsigned long long
#define solid const auto &
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<LL,LL>
#define fi first
#define se second
#define gm int mid((l+r)/2)
#define space putchar(' ')
#define enter putchar('\n')
#define rd() ({ri t;in(t);t;})
#define Size(x) ((int)x.size())
#define mem(x,y) memset(x,y,sizeof(x))
template<class T>il void in(T &x)
{
	x=0; char c=getchar(); bool f=0;
	while(!isdigit(c)) f|=(c=='-'),c=getchar();
	while(isdigit(c)) x=x*10+(c^'0'),c=getchar();
	f?x=-x:0;
}
template<class T>il void out(T x,const char c='\n')
{
	static short st[30]; short m=0;
	if(x<0) putchar('-'),x=-x;
	do st[++m]=x%10,x/=10; while(x);
	while(m) putchar(st[m--]|'0');
	putchar(c);
}
template<class T>il void err(const T &x,const char c='\n') {cerr<<x<<c;}
template<class T,class ...Args>il void in(T &x,Args &...args) {in(x); in(args...);}
template<class T,class ...Args>il void out(const T &x,const Args &...args) {out(x,' '); out(args...);}
template<class T,class ...Args>il void err(const T &x,const Args &...args) {err(x,' '); err(args...);}
template<class T>il void prt(T a[],int n) {for(ri i=0; i<n; ++i) out(a[i],i==n-1?'\n':' ');}
template<class T>il void clr(T a[],int n) {memset(a,0,sizeof(T)*n);}
template<class T>il void clr(T *a,T *b) {memset(a,0,sizeof(T)*(b-a));}
template<class T>il bool ckmax(T &a,const T &b) {return a<b?a=b,1:0;}
template<class T>il bool ckmin(T &a,const T &b) {return a>b?a=b,1:0;}
namespace MOD_CALC
{
const int md=66662333,inv2=(md+1)/2;
il int add(const int a,const int b) {return a+b>=md?a+b-md:a+b;}
il int sub(const int a,const int b) {return a-b<0?a-b+md:a-b;}
il int mul(const int a,const int b) {return (LL)a*b%md;}
il void inc(int &a,const int b) {(a+=b)>=md?a-=md:0;}
il void dec(int &a,const int b) {(a-=b)<0?a+=md:0;}
il int qpow(int a,int b) {int r=1; for(; b; b>>=1,a=mul(a,a)) if(b&1) r=mul(r,a); return r;}
il int qpow(int a,int b,const int p) {int r=1; for(; b; b>>=1,a=(LL)a*a%p) if(b&1) r=(LL)r*a%p; return r;}
il int mdinv(const int a) {return qpow(a,md-2);}
template<class ...Args>il int add(const int a,const int b,const Args &...args) {return add(add(a,b),args...);}
template<class ...Args>il int mul(const int a,const int b,const Args &...args) {return mul(mul(a,b),args...);}
} using namespace MOD_CALC;
namespace i207M
{
#pragma endregion

LL n,l,r,len,k;
il void gun(LL ans) {out(ans); exit(0);}
signed main()
{
#ifdef M207
	freopen("in.in","r",stdin);
	// freopen("ot.out","w",stdout);
#endif
	in(n,l,r,k); len=(l<=r?r-l+1:n-(l-r)+1);
	if(n<=1000000)
	{
		// for each ans
		for(LL a=n; a>=1; --a)
		{
			LL r=k%(n+a);
			if(!r)
			{
				if(len==n) gun(a);
			}
			else
			{
				LL b=r-len;
				if(b>=0&&b<=len&&b>=a-(n-len)&&b<=a) gun(a);
			}
			r=(k+1)%(n+a);
			if(!r)
			{
				if(len==n) gun(a);
			}
			else
			{
				LL b=r-len;
				if(b>0&&b<=len&&b>=a-(n-len)&&b<=a) gun(a);
			}
		}
		if(k%n==len) gun(0);
		gun(-1);
	}
	else
	{
		// for each circle
		LL ans=-1;
		// special for 0
		if(k+1<=2*len) ckmax(ans,k+1-len+n-len); // WARN
		else if(k<=2*len) ckmax(ans,k-len+n-len);
		for(LL c=1; len+c*n<=k; ++c)
		{
			LL t=k-len-c*n,a=t/c,b=t-a*c,d=max(a-n,0ll); // WARN
			a-=d,b+=d*c;
			if(a>b+n-len)
			{
				LL w=(a-b-n+len+c)/(c+1); // WARN
				a-=w,b+=w*c;
			}
			if(b<=a&&b<=len&&a>=0) ckmax(ans,a);
		}
		for(LL c=1; len+c*n<=k+1; ++c)
		{
			LL t=k+1-len-c*n,a=t/c,b=t-a*c,d=max(a-n,0ll);
			if(b==0) ckmax(d,1ll);
			a-=d,b+=d*c;
			if(a>b+n-len)
			{
				LL w=(a-b-n+len+c)/(c+1);
				a-=w,b+=w*c;
			}
			if(b>0&&b<=a&&b<=len&&a>=0) ckmax(ans,a);
		}
		gun(ans);
	}
	return 0;
}
#pragma region
}
signed main()
{
	i207M::main();
	return 0;
}
#pragma endregion

#include<bits/stdc++.h>
using namespace std;

typedef long long int64;

namespace Template{
	const int L = (1 << 21) | 1;
	char ibuf[L], obuf[20], *iS, *iT, *oT = obuf;

	inline char gc(){
		if(iS == iT){
			iT = (iS = ibuf) + fread(ibuf, 1, L, stdin);
			if(iS == iT)
				return EOF;
		}
		return *iS++;
	}

	#ifndef ONLINE_JUDGE
		#define gc getchar
	#endif

	template<class I>
	void gi(I &ret){
		static char ch;
		while(ch = gc(), !isdigit(ch)) ;
		ret = ch - '0';
		while(ch = gc(), isdigit(ch))
			ret = ret * 10 + ch - '0';
	}

	template<class I>
	void print(I ret){
		if(ret < 0)
			putchar('-'), ret = -ret;
		do
			*oT++ = ret % 10 + '0', ret /= 10;
		while(ret);
		while(oT != obuf)
			putchar(*(--oT));
	}

    template<class I> void scan(I &t) { gi(t); }
    template<class I> void debug(I t) { cerr << t << endl; }
    template<class I, class ...Args> void scan(I &x, Args &...rest) {  gi(x); scan(rest...); }
    template<class I, class ...Args> void debug(I x, Args ...rest) { cerr << x << " "; debug(rest...); }

    template<class I> I min(I x){ return x; }
    template<class I, class ...Args> I min(I x, Args ...rest) { return std::min(x, min(rest...)); }
    template<class I> I max(I x){ return x; }
    template<class I, class ...Args> I max(I x, Args ...rest) { return std::max(x, max(rest...)); }
    template<class I> I sum(I x){ return x; }
    template<class I, class ...Args> I sum(I x, Args ...rest) { return x + sum(rest...); }

	// \lceil \frac{x}{y} \rceil (x \geq 0, y > 0)
	template<class I> inline I pge(I x, I y){ return (x + y - 1) / y; }
	// \lfloor \frac{x}{y} \rfloor (x \geq 0, y > 0)
	template<class I> inline I ple(I x, I y){ return x / y; }
	// \lceil \frac{x}{y} \rceil (y > 0)
	template<class I> inline I ge(I x, I y){ return (x > 0) ? pge(x, y) : -ple(-x, y); }
	// \lfloor \frac{x}{y} \rfloor (y > 0)
	template<class I> inline I le(I x, I y){ return (x > 0) ? ple(x, y) : -pge(-x, y); }
}
using Template::scan;
using Template::print;
using Template::debug;
using Template::min;
using Template::max;
using Template::ge;
using Template::le;

int64 Ans(-1);
int64 n, l, r, k, len;

void check(int64 w){
	if(w < n || w > 2 * n)
		return;
	Ans = max(Ans, w - n);
}

void method1(){
	//len == n
	for(int i = 1; 1ll * i * i <= k; i++){
		if(k % i != 0)
			continue;
		check(static_cast<int64>(i)), check(k / i);
	}
	++k;
	for(int i = 1; 1ll * i * i <= k; i++){
		if(k % i != 0)
			continue;
		check(static_cast<int64>(i)), check(k / i);
	}
}

void method2(){
	for(int rest, i = 0; i <= n; i++){
		rest = k % (i + n);
		if(rest < len || rest > 2 * len)
			goto fail1;
		rest -= len;
		if(i - rest > n - len || i < rest)
			goto fail1;
		Ans = max(Ans, static_cast<int64>(i));

		fail1:
			;

		rest = (k + 1) % (i + n);
		if(rest <= len || rest > 2 * len)
			goto fail2;
		rest -= len;
		if(i - rest > n - len || i < rest)
			goto fail2;
		Ans = max(Ans, static_cast<int64>(i));

		fail2:
			;
	}
}

void method3(){
}

int main(){
	scan(n, l, r, k);
	len = r - l + 1, len = len < 0 ? (len + n) : len;

//	debug(k, len);
	if(len == n)
		method1();
	else if(n <= 1000000ll)
		method2();
	else method3();

	print(Ans);

	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, l, r, k, a;
signed main() {
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    a = (r - l + n + 1) % n;
    int ans = -1;
    for (int i = 1, j; i <= k; i = j + 1) {
        int cnt = k / i;
        j = k / cnt;
        int lp = max(n, i);
        int rp = min(2 * n, j);
		lp = max(lp, (k - 2 * a + cnt - 1) / cnt);
		rp = min(rp, min((2 * n + k - 2 * a + 1) / (cnt + 1), (k - a) / cnt));
        if (lp <= rp) ans = max(ans, rp - n);
    }
    if (k >= a && k >= a * 2) ans = max(ans, min(a, k - a + 1) + (n - a));
    if (!a && k == n) ans = max(ans, 1ll);
    printf("%lld\n", ans);
    return 0;
}

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <iostream>
#include <bitset>
using namespace std;
#define ll long long
ll n,k,l,r;
void ex_gcd(ll a,ll b,ll &x,ll &y)
{
	if(!b){x=1,y=0;return ;}
	ex_gcd(b,a%b,x,y);ll t=x;x=y;y=t-a/b*y;
}
int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	if(l>r)r=n-l+r+1,l=1;
	else r=r-l+1,l=1;
	if(n<=1000000)
	{
		ll ans=-1;
		for(int bit=1;bit<=2;bit++)for(int lt=1;lt<=bit;lt++)
		{
			for(int i=n+bit-1;i<=n*2;i++)
			{
				ll t=k/i;ll y=k%i;
				if(r==n)
				{
					if((y+lt-1)%i==0)ans=max(i-n,ans);
					continue;
				}
				// printf("%lld\n",y);
				if(i-n-(y-r+bit-lt)>n-r||y-r>i-n||y-r+1<lt||y>(r-1)*2+lt)continue;
				ans=max(i-n,ans);
			}
		}
		printf("%lld\n",ans);
	}else
	{
		ll lim=k/n,ans=-1;
		for(int bit=1;bit<=2;bit++)for(int lt=1;lt<=bit;lt++)
		{
			if(k<=r*2-2+lt)ans=max(ans,k-r+bit-1+n-r);
			for(int i=1;i<=lim;i++)
			{
				ll y=k/i;ll x=k%i;
				if(x<r-1+lt)
				{
					ll t=(r-2+lt-x)/i+1;
					x+=t*i;y-=t;
				}
				if(y>2*(n-1)+bit)
				{
					ll t=((y-x+lt-bit)-2*(n-r)-1)/(i+1)+1;
					x+=t*i;y-=t;
				}
				if(x>y)continue;
				if(r==n)
				{
					if((y-x-bit+lt)%(i+1)==0)
					{
						ll t=(y-x-bit+lt)/(i+1);
						x+=t*i;y-=t;
					}
					if((!x&&lt==bit)||x+bit-lt==y)ans=max(ans,y-n);
					continue;
				}
				if(y>2*(n-1)+bit||(y<n-1+bit&&y!=0))continue;
				if(x>(r-1)*2+lt||(x<r-1+lt&&x!=0))continue;
				ans=max(y-n,ans);
			}
		}
		printf("%lld\n",ans);
	}
}

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<bitset>
#include<set>
#include<cstdlib>
#include<complex>
#include<list>
#include<cassert>
#include<iomanip>
#include<limits>
#include<fstream>
#include<unordered_map>

using namespace std;

//#define double long double

typedef pair<int,int> ii;
typedef pair<int,long long> il;
typedef pair<long long,long long> ll;
typedef pair<ll,int> lli;
typedef pair<long long,int> li;
typedef pair<double,double> dd;
typedef pair<ii,int> iii;
typedef pair<double,int> di;
typedef pair<int,ii> iii2;
typedef pair<ii,ii> iiii;
typedef vector<int> vi;
long long mod = 1000000007;
long long large = 2000000000000000000LL;

int main(){

	long long n,k,l,r;
	cin>>n>>l>>r>>k;

	l--;
	r%=n;
	long long g = 0;

	if(r>=l) g = r-l;
	else g = n-l+r;

	long long ans = -1;

	for(long long i=1;i<=min(1000000LL,n);i++){
		long long re = k%(n+i);
		if(re>=g){
			long long y = re-g;
			if(y<=g&&y<=i) ans = max(ans,i);
		}
	}

	for(long long i=0;i<=1000000;i++){
		if(i==0){
			long long y = k-g;
			if(y>=0&&y<=g){
				long long x = n-g+y;
				ans=max(ans,x);
			}
			continue;
		}
		long long remain = k-i*n-g;
		if(remain<0) continue;
		long long x = remain/i;
		long long y = remain%i;
		if(x<=n&&y<=g&&x-y<=n-g&&y<=x) ans = max(ans,x);
	}

	k++;
	for(long long i=1;i<=min(1000000LL,n);i++){
		long long re = k%(n+i);
		if(re>=g){
			long long y = re-g;
			if(y<=g&&y<=i) ans = max(ans,i);
		}
	}

	for(long long i=0;i<=1000000;i++){
		if(i==0){
			long long y = k-g;
			if(y>=0&&y<=g){
				long long x = n-g+y;
				ans=max(ans,x);
			}
			continue;
		}
		long long remain = k-i*n-g;
		if(remain<0) continue;
		long long x = remain/i;
		long long y = remain%i;
		if(x<=n&&y<=g&&x-y<=n-g&&y<=x) ans = max(ans,x);
	}

	cout<<ans<<endl;

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
long long n,l,r,k,x,y;
long long cal1(long long a,long long b)
{
    long long val = x+a;
    if(k==val || (a!=0 && k==val-1))
        return a+b;
    long long temp = k-val;
    val = x+a+y+b;
    if(temp%val==0 || (a!=0 && temp%val ==val-1))
        return a+b;
    return -1;
}
long long solve1()
{
    long long ans=-1;
    for(int i=0;i<=x;i++)
        for(int j=0;j<=y;j++)
            ans=max(ans,cal1(i,j));
    return ans;
}
long long lasthope(long long rem,long long hope)
{

}
long long cal2(long long t)
{
    if(t==0)
    {
        if(k-x<0)
            return -1;
        if(x-(k-x)<0)
            return -1;
        long long ans =y +  min((k-x)+1,x);
        return ans;
    }
    long long val = k-(n*t+x);
    if(val<0)
        return -1;
    long long hold = min(val / t,y);
    long long mul = val - hold*t;
    if(mul > (t+1)*x)
        return -1;
    long long rem = mul%(t+1),keep = mul/(t+1);
    if(t==1)
    {
        if(keep==0)
        {
            if(rem==0)
            {
                if(rem-t<=hold)
                    return hold+1;
                else
                    return hold;
            }
            if( rem-1 > hold)
                return -1;
            if( rem-1 > x)
                return -1;
            long long ans = hold+1;
            return ans;
        }
        else
        {
            if(rem==0)
            {
                if(rem-t<=hold && keep + rem-t<=x)
                    return keep + hold+1;
                else
                    return keep + hold ;
            }

            if( rem-1 > hold)
                return -1;
            if(keep+rem-1 > x)
                return -1;
            long long ans =keep +  hold+1;
            return ans;
        }
    }
    else
    {
        if(keep==0)
        {
            if(rem==0)
                return hold;
            if( rem > hold)
                return -1;
            if( rem > x)
                return -1;
            long long ans = hold;
            return ans;
        }
        else
        {
            if(rem==0)
                return keep + hold ;

            if( rem > hold)
                return -1;
            if(keep+rem > x)
                return -1;
            long long ans =keep +  hold;
            return ans;
        }
    }

}
long long solve2()
{
    long long t= k/n;
    long long ans=-1;
    for(int i=0;i<=t;i++)
        ans=max(ans,cal2(i));
    return ans;
}
int main(int argc, char const *argv[])
{
    cin>>n>>l>>r>>k;
    if(l<=r)
        x = r-l+1,y = n - x;
    else
    {
        y = l-r-1;
        x = n-y;
    }
    n<=7000 ? cout<<solve1()<<"\n": cout<<solve2()<<"\n";
    return 0;
}

#pragma GCC optimize("O2")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,sse,sse2,ssse3,popcnt,sse4.1,sse4.2,tune=native")
#include<bits/stdc++.h>
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define pb push_back
using namespace std;
using ll = long long;
//using arr = array;
using pi = pair<int, int>;
using vi = vector<ll>;
using vvi = vector<vi>;
using vpi = vector<pi>;
using ld = long double;
const int maxn = 1<<18, mod = 1e9 + 7 , lg = 19;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll n, l, r, k, d;
ll go(ll n, ll k, ll mn) {
	for(ll a = min(2*n, k); a >= n+mn; a--) {
		if(k%a == 0) return a-n;
	}
	return -1;
}
void solve1() {
	ll ans = -1;
	for(int s = 0; s <= d; s++) {
		ans = max(ans, go(n, k - d - s, s));
		if(s) ans = max(ans, go(n, k - d - s + 1, s));
	}
	cout << ans;
}
void solve2() {
	ll ans = -1;
	for(ll c = 1; c*n + d <= k; c++) {
		ll a = min(k - (k%c), 2*n*c)/c;
		ll s = k - a*c;
		if(s <= d) ans = max(ans, a-n);
	}
	cout << ans;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n >> l >> r >> k;
	d = (n + r - l + 1) % n;
	if(k <= 2*d) {
		cout << min(d, k - d + 1) + n - d;
		return 0;
	}
	if(k < n) return cout << -1, 0;
	if(n <= 4000) solve1();
	else solve2();
}

/*
 ID: bradyawn
 PROG: contest
 LANG: C++11
 */

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <fstream>
#include <vector>
#include <deque>
#include <string>
#include <cmath>
#include <map>
#include <unordered_map>
#include <utility>
#include <set>
#include <unordered_set>
#include <ctime>
#include <queue>
#include <stack>
#include <bitset>
#include <random>
#include <cstring>
#include <complex>
#include <cassert>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int,int> i2;
typedef pair<ll,ll> ll2;

ll n, l, r, k;

ll get(ll a, ll b) //left, right
{
    if (a <= b) return (b-a+1);
    else
    {
        //a > b
        return n-get(b,a)+2;
    }
}

void solvekn(ll a, ll b) //a, b O(k/n)
{
    ll ret = -1;

    //t = 0
    //try to maximize amount of 2's in a seats

    if (a <= k && k <= 2*a) ret = max(ret, min(n, (k-a)+(b)+1));

    for (ll t = 1; t <= k/n; t++)
    {
        ll k2 = k - a*(2*t+2) - 2*t*b;
        ll lb =  ceil(max((k2-b)/(t+1.0), (1.0*k2)/(t)));
        ll ub = floor(min((k2)/(t+1.0) , (1.0*a+k2)/(t)));
        if (lb > ub) continue;
        ll z = lb;
        ll A = a-(-k2 + t*z);
        ll B = b-(k2 - (t+1)*z);
        ret = max(ret, A+B);

        z = ub;
        A = a-(-k2 + t*z);
        B = b-(k2 - (t+1)*z);
        ret = max(ret, A+B);
    }

    for (ll t = 1; t <= k/n; t++)
    {
        ll k2 = k - a*(2*t+2) - 2*t*b + 1;
        ll lb =  ceil(max((k2-b)/(t+1.0), (1.0*k2)/(t)));
        ll ub = floor(min((k2)/(t+1.0) , (1.0*a+k2)/(t)));
        if (lb > ub) continue;
        ll z = lb;
        ll A = a-(-k2 + t*z);
        ll B = b-(k2 - (t+1)*z);
        if (A+B != 0) ret = max(ret, A+B);

        z = ub;
        A = a-(-k2 + t*z);
        B = b-(k2 - (t+1)*z);
        if (A+B != 0) ret = max(ret, A+B);
    }

    cout << ret << '\n';
}

void solven(ll a, ll b) //A*B
{
    ll ret = -1;
    for (ll a1 = 0; a1 <= a; a1++)
        for (ll b1 = 0; b1 <= b; b1++)
        {
            ll ka = (a1 + 2*(a-a1));
            ll kb = (b1 + 2*(b-b1));
            ll k2 = k - ka;
            if (k2 % (ka+kb) == 0) ret = max(ret, n-a1-b1);
        }

    //k+1
    for (ll a1 = 0; a1 <= a; a1++)
        for (ll b1 = 0; b1 <= b; b1++)
        {
            ll ka = (a1 + 2*(a-a1));
            ll kb = (b1 + 2*(b-b1));
            ll k2 = k - ka + 1;
            if (n-a1-b1 == 0) continue;
            if (k2 % (ka+kb) == 0) ret = max(ret, n-a1-b1);
        }

    cout << ret << '\n';
}

int main()
{
    //ifstream inf("");
    //ofstream outf("");
    cout << setprecision(10);
    ios::sync_with_stdio(0); cin.tie(0);

    cin >> n >> l >> r >> k;

    ll a = get(l, r);
    ll b = n-a;

    if (n*n < k/n) solven(a,b); //nn smaller
    else solvekn(a,b); //kn smaller

    return 0;

}

#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register ll i=a; i<=b; i++)
#define per(i,a,b) for (register ll i=a; i>=b; i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
inline void read(ll &x) {
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
inline ui R() {
	static ui seed=416;
	return seed^=seed>>5,seed^=seed<<17,seed^=seed>>13;
}
ll n,P,Q,k,l,res=-1;
//sum=k+1 && y
int main() {
	read(n);read(P);read(Q);read(k);l=Q-P+1;if(l<0)l+=n;
	if(n<=3000000){
		rep(x,0,n){
			ll y=(k-l)%(n+x),a=(k-l)/(n+x);
			if(y<=l&&y<=x&&x-y<=n-l&&k-l>=0&&x>=0&&y>=0&&a>=0)res=max(res,x);
		}
		k++;
		rep(x,0,n){
			ll y=(k-l)%(n+x),a=(k-l)/(n+x);
			if(y<=l&&y<=x&&x-y<=n-l&&k-l>=0&&x>=0&&y>0&&a>=0)res=max(res,x);
		}
		cout<<res;
		return 0;
	}
	rep(a,1,k/n){
		ll c=k-l-a*n;//ax+y=c
		if(c<0)continue;
		ll x=c/a,y=c-a*x;
		if(y<0){
			ll xs=-y/a;x-=xs;y+=xs*a;
			while(y<0)x--,y+=a;
		}
		if(x-y>n-l){
			ll xs=(x-y-(n-l))/(a+1);x-=xs;y+=xs*a;
			while(x-y>n-l)x--,y+=xs;
		}
		if(x>=0&&y>=0&&y<=l&&x-y>=0&&x-y<=n-l)res=max(res,x);
	}
	ll y=k-l,x=y+n-l;
	if(x>=0&&y>=0&&y<=l&&x-y>=0&&x-y<=n-l)res=max(res,x);
	k++;
	rep(a,1,k/n){
		ll c=k-l-a*n;//ax+y=c
		if(c<0)continue;
		ll x=c/a,y=c-a*x;
		if(y<=0){
			ll xs=-y/a;x-=xs;y+=xs*a;
			while(y<=0)x--,y+=a;
		}
		if(x-y>n-l){
			ll xs=(x-y-(n-l))/(a+1);x-=xs;y+=xs*a;
			while(x-y>n-l)x--,y+=xs;
		}
		if(x>=0&&y>0&&y<=l&&x-y>=0&&x-y<=n-l)res=max(res,x);
	}
	y=k-l,x=y+n-l;
	if(x>=0&&y>=0&&y<=l&&x-y>=0&&x-y<=n-l)res=max(res,x);
	cout<<res;return 0;
}

#include<bits/stdc++.h>
#define rep(i,x,y) for(int i=(x);i<=(y);i++)
#define dep(i,x,y) for(int i=(x);i>=(y);i--)
#define N 2010
#define ll long long
#define pb push_back
#define add(x,y) x=(x+(y))%mo;
#define sqr(x) ((x)*(x))
#define mo 1000000007
#define inf 1000000000
#define eps 1e-8
using namespace std;
ll n,l,r,k,i,ans;
int main(){
	scanf("%I64d%I64d%I64d%I64d",&n,&l,&r,&k);
	r=(r+n-l+1)%n;
	if(k<r){printf("-1");return 0;}
	if(2*r>=k){
		ans=min(k+n-r*2+1,n);
		if(ans>=k-r){printf("%I64d",ans);return 0;}
	}
	for(i=1;i<=k;i++){
		l=max((k-n*i-r-1)/(i+1),(k-n*i-r*2-1)/i)+1;
		ans=min(min((k-n*(i-1)-r*2+1)/(i+1),(k-n*i-r)/i),n);
		if(ans>=l){
			printf("%I64d",ans);return 0;
		}
		if(i*i>=k)break;
	}i=min(i,n);
	for(;i>=0;i--){
		l=k%(n+i)-r;
		if((l<=min(i,r))&&(l>=max(i+r-n-1,0ll))){
			printf("%I64d",i);return 0;
		}
	}
	printf("-1");
}

#include <bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;

long long n, l, r, k;
const int rlimit = 1e6;
long long ans = -1;
int main()
{
	scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
	long long mu = (r - l + n) % n + 1;
	if (k >= mu && k <= 2 * mu)
	{
		ans = (n - mu) + (k - mu);
		if (ans < n)
		{
			ans++;
		}
	}
	if (ans < 0)
	{
		long long tk = k - mu;
		if (n < k / n)
		{
			for (long long i = n; i >= 0 && ans < 0; i--)
			{
				long long b = (tk + 1) % (n + i);
				if (b <= i && b <= mu && (i - b) <= n - mu && b)
				{
					if(i > ans)
						ans = i;
				//	break;
				}
				b = tk % (n + i);
				if (b <= i && b <= mu && (i - b) <= n - mu)
				{
					if(i > ans)
						ans = i;
					//break;
				}
			}
		}
		else
		{
			long long kn = k / n;
			for (int i = 1; i <= kn && ans < 0; i++)
			{
				long long ttk = tk - n * i;
				if (ttk + 1 < 0)
					break;

				if (ttk + 1 > 0)
				{
					long long tmp = (ttk + 1) / i;
					if ((ttk + 1) % i == 0)
						tmp--;
					long long x = min((n - mu + ttk + 1) / (i + 1), tmp);

					if (ttk > x*(i + 1))
						x = 0;
					if (x && x > ans)
						ans = x;
				}
				if (ttk >= 0)
				{
					long long x = min((n - mu + ttk) / (i + 1), ttk / i);
					if (ttk > x*(i + 1))
						x = 0;
					if (x && x > ans)
						ans = x;
					else if (ttk == 0 && ans < 0)
					{
						ans = 0;
					}
				}
			}
		}
	}
	printf("%lld\n", ans);
}

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
ll n,K,l,r,ans=-1;
int main(){
	scanf("%I64d%I64d%I64d%I64d",&n,&l,&r,&K);
	ll len=(r-l+n)%n+1;
	if(n<=2e6){
		for(ll i=n,j;i>=0;i--){
			ll in=(K-len)%(n+i);
			if(len-(in+1)>n-i||in<0||in>i||in>len) continue;
			ll real=in+1;
			if(real<=i&&real<=len&&i>ans)ans=i;
			if(len-in<=n-i&&i>ans)ans=i;
			if(ans!=-1) break;
		}
	}else{
		ll up=K/n;
		for(ll r=0;r<=up;r++){
			ll i=(K-(r-1)*n+1-(len<<1))/(r+1);
			ll in=(K-r*(n+i)-len);
			if(in<0){
				if(!i) continue;
				ll res=(-in-1)/r+1;
				in+=res*r;i-=res;
			}
			if(i>n){
				in+=(i-n)*r;i=n;
			}
			if(len-(in+1)>n-i||in<0||in>i||in>len) continue;
			ll real=len+1;
			if(real<=i&&real<=len&&ans<i)ans=i;
			if(len-in<=n-i&&ans<i)ans=i;
		}
	}
	printf("%I64d\n",ans);
	return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

    if (K < Q) {
        cout << "-1\n";
        return;
    }

    ll ans = -1;

    if (K <= 2*Q) {
        cout << min(N, K-Q + 1 + (N-Q)) << endl;
        return;
    }

    for (ll rev = 1; rev <= 1000000; ++rev) {
        for (ll take : {(K - Q) / rev-1, (K-Q)/rev, (K-Q)/rev+1,
                        (K-Q-N)/(rev+1)-1, (K-Q-N)/(rev+1), (K-Q-N)/(rev+1)+1,
                        (K - 2*Q) / rev-1, (K-2*Q)/rev, (K-2*Q)/rev+1
        }) {
            ll s = take - N;
            if (s < 0) continue;
            if (s > N) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0) continue;
            if (left > Q) continue;
            if (left > s) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    for (ll take = 1; take <= 1000000; ++take) {
        if (take < N) continue;
        if (take > 2 * N) continue;
        ll s = take - N;
        for (ll rev = (K - 2*Q) / take - 1; rev <= (K-Q) / take + 1; ++rev) {
            if (rev <= 0) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0) continue;
            if (left > Q) continue;
            if (left > s) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define re register int
#define rep(i,a,b) for(re i=a;i<=b;++i)
#define _ 0
typedef long long ll;
long long n, k, l, r;

long long solve(ll n, ll r, ll k, int p) {
	if(k < r)	return -1;
	long long s=0;
	if(n > k/n/n) {
		if(k<=2*r)	return k-r+n-r;

		for(ll t=max((k-2*r-1)/(2*n)+1,1ll); t<=(k-r)/n; ++t) { //枚举圈数t
			ll a = (k-r)%t;
			if(a < p)	a+=t;
			ll b = (k-r-a)/t - n-a;
			if(b > n-r) {
				ll x = (b-n+r-1)/(t+1) + 1;
				a += t*x;
				b -= (t+1)*x;
			}
			if(a<=r && b>=0)	s=max(s, a+b);
		}
		// O(n/k)
	}
	else {
		for(ll a=p; a<=r; ++a)for(ll b=0; b<=n-r; ++b)
			if((k-r-a)%(n+a+b)==0)	s=max(s, a+b);
		// O(n^2)
	}
	return s;
}

int main() {
	cin >> n >> l >> r >> k;
	r = (r-l+n+1)%n;
	cout << max(solve(n,r,k,0),solve(n,r,k+1,1)) << endl;
	return ~~(0^_^0);
}

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

const ll SQ = 1e6;

ll N, L, R, K, D, ans = -1;

void solve(ll t, ll K) {
    if(N > SQ) {
        for(ll i = 0; i <= SQ; i++) {
            if(N * i + D > K) break;

            ll R = K - N * i - D;

            ll s = t, e = N, p = -1;
            while(s <= e) {
                ll m = (s + e)>>1;

                ll le = m * i + max(t, m - N + D);
                ll ri = m * i + min(D, m);
                if(ri < R) {
                    s = m + 1;
                    continue;
                }
                if(R < le) {
                    e = m - 1;
                    continue;
                }
                p = m;
                s = m + 1;
            }
            if(p != -1) {
                ans = max(ans, p);
            }
        }
        return;
    }

    if(K - D < 0) return;

    for(ll i = t; i <= N; i++) {
        ll R = K - D;
        ll rem = R % (N + i);

        ll le = max(t, i - N + D);
        ll ri = min(D, i);

        if(le <= rem && rem <= ri) {
            ans = i;
        }
    }
}

int main() {
    cin >> N >> L >> R >> K;

    D = (R + N - L) % N + 1;

    solve(0, K);
    solve(1, K + 1);

    cout << ans;
}

#include <string.h>
#include <sstream>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <bitset>
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <queue>
#include <set>

#include <map>
#include <vector>
#include <string>
#include <stdlib.h>

#define ll long long
#define clr(x) memset(x,0,sizeof(x))
#define _clr(x) memset(x,-1,sizeof(x))
#define fr(i,a,b) for(int i = a; i < b; ++i)
#define frr(i,a,b) for(int i = a; i > b; --i)
#define pb push_back
#define sf scanf

#define pf printf
#define mp make_pair

using namespace std;

ll n,l,r,k;

ll check(ll n,ll len, ll k, ll i) {
	ll t =  k - n * i-len;
	//printf("n = %lld len = %lld k = %lld i = %lld\n",n,len,k,i);
	//printf("t = %lld t-len = %lld x = %lld n-len + t = %lld\n",t,t-len,i,n-len+t);
	//printf("%lld >=a >= %lld\n",(t)/i, (t-len)/i);
	//printf("%lld >=b >= %lld\n",(n-len+t)/(i+1), t/(i+1));
	if((t-len) <= t && (n-len+t)>=t && ( !( t/i < (t/(i+1) ) || (t-len)/i > (n-len+t)/(i+1) ))) {
		ll tmp = min(t/i, (n-len+t)/(i+1));
		ll a = t-tmp;
		ll b = -t + 2 * tmp;
		//printf("tmp = %lld a = %lld b = %lld\n",tmp,a,b);
		return tmp;
	}
	return -1;
}

int main() {
	cin>>n>>l>>r>>k;

	//(x+1)*a+x*b=k-n*x
	ll ans = -1;
	ll len = (r+n-l+1)%n;
	if(len==0)len = n;
	if(n<1000) {
		//a+x*(a+b)=k-n*x-len
		//x*(a+b+n)=k-a-len
		for(ll a = 0; a <= len&&k-a>=0; ++a) {
			for(ll b = 0; b <=(n-len); ++b) {
				//printf("a = %lld b = %lld\n",a,b);
				if(a+b==0) {
					if(k==0) {
						ans = 0;
					}
					continue;
				}
				ll x = (k-a-len);
				if(x%(a+b+n)==0 || x%(a+b+1+n)==0) {
					ans = max(ans,a+b);
				}
			}
		}
	}
	else {
		//a*(x+1) + b*x=k-x*n
		//
		// t = k-x*n
		// a = t, b = -t
		// t*(x+1)-t*x = t
		// a = t + -x * i
		// b = -t + (x+1)*i
		// (t-i*x)*(x+1)+((x+1)*i-t)*x
		//## t*(x+1)-(x+1)*x*i + (x+1)*i*x - x*t = t
		// len >= a >=0
		// n-len >= b >=0
		// len >= t-x*i >=0
		// n-len >= -t + (x+1)*i >=0
		// (t-len)/x <= i <= t/x
		// (n-len+t)/(x+1) >=i >= t/(x+1)
		// a + b = (-x*i+(x+1)*i) = i
		for(ll i = 0; i <= k/n; ++i) {
			if(i==0) {
				if(k<=2*len) {
					if(k<len) {
						break;
					}
					//printf("k = %lld len = %lld\n",k,len);
					ll a = min(k-len+1,len);
					ll b = n-len;
					//printf("a = %lld b = %lld\n",a,b);
					ans = max(ans,a+b);
				}
			}
			else {
				ll t =  k - n * i-len;
				if(t<0) {
					break;
				}
				ans = max(ans, check(n,len,k,i));
				ans = max(ans, check(n,len,k-i,i));

					/*
				ll t =  k - n * i-len;
				printf("n = %lld len = %lld\n",n,len);
				printf("t = %lld t-len = %lld x = %lld n-len + t = %lld\n",t,t-len,i,n-len+t);
				printf("%lld >=a >= %lld\n",(t)/i, (t-len)/i);
				printf("%lld >=b >= %lld\n",(n-len+t)/(i+1), t/(i+1));
				if((t-len) <= t && (n-len+t)>=t && ( !( t/i < (t/(i+1) ) || (t-len)/i > (n-len+t)/(i+1) ))) {
					ll tmp = min(t/i, (n-len+t)/(i+1));
					ll a = t-tmp;
					ll b = -t + 2 * tmp;
					printf("tmp = %lld a = %lld b = %lld\n",tmp,a,b);
					ans = max(ans, tmp);
				}
				*/
			}
		}
	}
	cout<<ans<<endl;
}

#include<bits/stdc++.h>
using namespace std;

#define F(i,a,b) for(int i=a;i<=b;i++)
#define D(i,a,b) for(int i=a;i>=b;i--)
#define ms(i,a)  memset(a,i,sizeof(a))
#define LL       long long
template<class T>void read(T &x){
	x=0; char c=getchar();
	while (c<'0' || c>'9') c=getchar();
	while (c>='0' && c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
}
template<class T>void write(T x){
	if(x<0) x=-x,putchar('-');
	if(x>9) write(x/10);
	putchar(48+x%10);
}
template<class T>void chkmax(T &x,T y){ x=x>y? x:y; }
LL n,k,l,r,x,t,s,p,ans,y;
LL const inf=1LL<<50;
LL calc(LL p,LL s,int a,int b){
	if(a==0 || b==1){
		if(k-s-x>=0 && (k-s-x)%(n+p)==0)
			return p;
		else return -1;
	}else {
		if(k-s+1-x>=0 && (k-s+1-x)%(n+p)==0)
			return p;
		else return -1;
	}
}

LL exgcd(LL &x,LL &y,LL a,LL b){
	if(!b){
		x=1;y=0; return a;
	}
	LL t=exgcd(y,x,b,a%b);
	y-=a/b*x;
	return t;
}
void solve(LL t1,LL t2,LL c,LL add){
//	cout<<t1<<" "<<t2<<" "<<c<<endl;
	if(t2==0){
		//cout<<"###"<<endl;
		if(2*x>=k) chkmax(ans,min(x,k-x+1)+y);
		return;
	}
	LL a,b;
	LL g=exgcd(a,b,t1,t2);
	a=a*c; b=b*c;
	LL l=-inf,r=inf;
	a-=add;
	if (a>=0) r=min(r,a/t2); else  r=min(r,(a-t2+1)/t2);
	if(a-x>=0) l=max(l,(a-x+t2-1)/t2); else l=max(l,(a-x)/t2);
	if(y-b>=0) r=min(r,(y-b)/t1); else r=min(r,(y-b-t1+1)/t1);
	if(-b>=0) l=max(l,(-b+t1-1)/t1); else l=max(l,-b/t1);
	//cout<<l<<" "<<r<<endl;
	if(l<=r){
		chkmax(ans,a+b+l);
		chkmax(ans,a+b+r);
	}
}
int main(){
	read(n);
	read(l);
	read(r);
	read(k);
	x=(r-l+n)% n+1;
	y=n-x;
	ans=-1;
	if(k/n>10000000){
		F(p,0,n) F(s,max(0LL,x-(n-p)),min((int)x,p)){
			if(s<x) chkmax(ans,calc(p,s,0,0));
			if(s)chkmax(ans,calc(p,s,1,0));
			//cout<<p<<" "<<s<<" "<<ans<<endl;
			if(s)chkmax(ans,calc(p,s,1,1));
			//cout<<p<<" "<<s<<" "<<ans<<endl;
		}
	}else {
		F(t,0,k/n){
			solve(t+1,t,k-t*x-x-t*y,0);
			solve(t+1,t,k-t*x-x-t*y+1,1);
	//		cout<<0<<" "<<ans<<endl;
		}
	}
	write(ans);
	return 0;
}

#include<cstdio>
//in: a,x out: b,y
//x+a+t(n+a+b) = k
long long partOne(long long n,long long l,long long r,long long k,int mode){
    long long res = -1;
    long long x = r-l+1;
    if(x<0) x = l-r+1;
    long long y = n-x;
    long long sa = 0;
    if(mode) sa = 1;
    for(long long a = sa; a <= x; a++){
        for(long long b = 0; b <= y; b++){
            long long left = k-x-a;
            long long cycle = n+a+b;
            if(left>=0 && left%cycle==0){
                long long offer = a+b;
                if(res<offer) res = offer;
            }
        }
    }
    return res;
}

void exGcd(long long a,long long b,long long& x,long long& y){
    if(b==0) x = 1, y = 0;
    else{
        exGcd(b,a%b,x,y);
        long long t = x;
        x = y;
        y = t-(a/b)*x;
    }
}

//c <= k*mul minK
long long getLower(long long mul,long long c){
    if(c%mul==0) return c/mul;
    else{
        if(c>=0) return (c/mul)+1;
        else{
            long long res = (-c)/mul;
            return -res;
        }
    }
}
//k*mul <= c maxK
long long getUpper(long long mul,long long c){
    if(c%mul==0) return c/mul;
    else{
        if(c>=0) return c/mul;
        else{
            long long res = (-c)/mul;
            return -res-1ll;
        }
    }
}

//upper
//mode = lowerU
//cx0+kcb, cy0-kca
long long solveEq(long long a,long long b,long long c,long long ux,long long uy,int mode){
    long long x0,y0;
    exGcd(a,b,x0,y0);
    long long lower = 0-c*x0;
    if(mode) lower++;
    long long minK = getLower(b,lower);
    long long maxK = getUpper(b,ux-c*x0);
    long long resK = getLower(a,c*y0-uy);
    if(minK<resK) minK = resK;
    resK = getUpper(a,c*y0);
    if(maxK>resK) maxK = resK;
    if(minK<=maxK){
        long long take = -1;
        if(b>=a) take = maxK;
        else take = minK;
        return c*(x0+y0)+take*(b-a);
    }
    else return -1;
}

//be careful on last one is 2 but pick 1
//x+a+t(n+a+b) = k
long long partTwo(long long n,long long l,long long r,long long k,int mode){
    long long res = -1;
    long long x = r-l+1;
    if(x<0) x = l-r+1;
    long long y = n-x;
    for(long long t = 1; t*n <= k; t++){
        long long c = k-t*n-x;
        long long offer = -1;
        if(c<0) offer = -1;
        else if(c==0){
            if(!mode) offer = 0;
            else offer = -1;
        }
        else offer = solveEq(t+1,t,c,x,y,mode);
        //printf("%lld %lld %lld %lld %lld\n",t+1,t,c,x,y);
        if(res<offer) res = offer;
        //printf("t = %lld, offer = %lld\n",t,offer);
    }
    //sp judge on t = 0
    if(x<=k){
        long long a = k-x;
        if(a<=x && a>=mode){
            long long b = y;
            if(res<a+b) res = a+b;
        }
    }
    return res;
}

int main(){
    long long up = 200000000000;
    long long n,l,r,k;
    scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
    //printf("%lld\n",partOne(n,l,r,k,0));
    //printf("%lld\n",partOne(n,l,r,k+1,1));
    //printf("%lld\n",partTwo(n,l,r,k,0));
    //printf("%lld\n",partTwo(n,l,r,k+1,1));
    long long ans = -1; long long res = -1;
    if(n<=up){
        res = partOne(n,l,r,k,0);
        if(ans<res) ans = res;
        res = partOne(n,l,r,k+1,1);
        if(ans<res) ans = res;
    }
    else{
        res = partTwo(n,l,r,k,0);
        if(ans<res) ans = res;
        res = partTwo(n,l,r,k+1,1);
        if(ans<res) ans = res;
    }
    printf("%lld\n",ans);
    return 0;
}

/**************************************************************
    Problem: ????
    User: Big_Red_Dates
    Language: GNU_C++11
    Result: Accepted
    Time:0 ms
    Memory:0 kb
    length:0 kb
    score: inf
****************************************************************/
//CLOCKS_PER_SEC
using namespace std;
#include<bitset>
#include<deque>
#include<stdint.h>
#include<set>
#include<stack>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<iomanip>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<ctime>
#include<map>
#define sqr(x) (x)*(x)
#define sort stable_sort
#define ll long long
#define mk make_pair
#define pb push_back
#define in insert
#define mtr(x,y,z) mk(mk(x,y),z)
#define fi first
#define se second
#define lch(x) ((x)<<1)
#define rch(x) (((x)<<1)|1)
#define all(x) (x).begin(),(x).end()
#define titose CLOCKS_PER_SEC
#define fpi(x) freopen(x,"r",stdin);
#define fpo(x) freopen(x,"w",stdout);
#define fprio fpi("in.txt");fpo("out.txt");
#define fast ios_base::sync_with_stdio(false);
inline void read(int &x){int v=0,f=1;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=v*10+c-'0';while (isdigit(c=getchar())) v=v*10+c-'0';x=v*f;}
inline void read(ll &x){ll v=0ll,f=1ll;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=v*10+c-'0';while (isdigit(c=getchar())) v=v*10+c-'0';x=v*f;}
inline void readc(char &x){char c;while ((c=getchar())==' ');x=c;}
inline void writes(string s){puts(s.c_str());}
inline void writeln(){writes("");}
inline void writei(int x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
inline void writell(ll x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
/*
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)
#pragma GCC optimize(5)
#pragma GCC optimize(6)
#pragma GCC optimize(7)
#pragma GCC optimize(8)
#pragma GCC optimize(9)
*/
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define vl vector<ll>
#define si set<int>
#define sl set<ll>
#define mii map<int,int>
#define mll map<ll,ll>
#define msi map<string,int>
#define msl map<string,ll>
#define piii pair<int,pii >
#define piipi pair<pii,int>
#define plll pair<ll,pll >
#define pllpl pair<pll,ll>
#define pqi priority_queue<int>
#define pql priority_queue<ll>
#define npqi priority_queue<int,vector<int>,greater<int> >
#define npql priority_queue<ll,vector<ll>,greater<ll> >
#define forup(i,csc,lys) for ((i)=(csc);(i)<=(lys);(i)++)
#define fordo(i,csc,lys) for ((i)=(csc);(i)>=(lys);(i)--)
#define rep(i,x) forup ((i),1,(x))
#define repd(i,x) fordo ((i),(x),1)
#define itr iterator
#define lyscsc(itcalc,c) for(__typeof((c).begin()) itcalc=(c).begin();itcalc!=(c).end();itcalc++)
#define NO {cout<<"-1";return 0;}
#define YES {cout<<"YES";return 0;}
#define y0 y000000000000000000000000000
#define y1 y111111111111111111111111111
#define j0 j000000000000000000000000000
#define j1 j111111111111111111111111111
#define cl0(a) memset((a),(0),(sizeof((a))))
#define clz(a) memset((a),(0x16),(sizeof((a))))
#define clf(a) memset((a),(-(0x16)),(sizeof((a))))
#define inf 0x3bbbbbbb
#define lnf 0x1bbbbbbbbbbbbbbbll
#define sqrt divi
#define p2(i) (1ll<<(i))
#define readi read
#define readll read
/*************************************************/
ll n,m,i,j,l,r,k,b=250000,ans=-1;
int main()
{
	cin>>n>>l>>r>>k;
	l=(r+n-l+1)%n;
	if (n<=b)
	{
		for (i=0;i<=n;i++)
		{
			ll t=k%(n+i);
			if (t>=l+min(l,max(0ll,i-(n-l)-1))&&t<=l+min(l,i))
			{
				ans=max(ans,i);
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <iostream>
#include <bitset>
using namespace std;
#define N 1000000
#define ll long long
ll n,k,l,r,t,x,y;
void ex_gcd(ll a,ll b)
{
	if(!b){x=1,y=0;return ;}
	ex_gcd(b,a%b);ll tmp=x;x=y;y=tmp-a/b*y;
}
int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	// if(n<=N)
	// {
	// 	ll ans=-1;
	// 	for(int i=n;i<=n*2;i++)
	// 	{
	// 		ll tmp=k/i;
	// 		t=k-tmp*i;printf("%d\n",t);
	// 		if(l==1&&r==n)
	// 		{
	// 			if(t==0)ans=max(i-n,ans);
	// 			continue;
	// 		}
	// 		if(t>i-n||t>(r-l+1)*2||(i-t)>(n-r+l-1)*2)continue;
	// 		ans=max(ans,i-n);
	// 	}
	// 	printf("%lld\n",ans);
	// }else
	// {
		int lim=k/n;ll ans=-1;
		if(k<(r-l+1)*2)return printf("%lld\n",k+1-(r-l+1)+n-(r-l+1)),0;
		else if(k==(r-l+1)*2)return printf("%lld\n",n),0;
		for(int i=1;i<=lim;i++)
		{
			ex_gcd(i+1,i);
			x=x*k,y=y*k;
			// printf("%d %lld %lld\n",i,x,y);
			if(x<r-l+1)
			{
				ll tmp=(r-l-x)/i+1;
				x=x+tmp*i;
				y=y-tmp*(i+1);
			}
			if(y>(n-r+l-1)*2)
			{
				ll tmp=(y-(n-r+l-1)*2-1)/(i+1)+1;
				x=x+tmp*i;
				y=y-tmp*(i+1);
			}
			if(x>(r-l+1)*2||y<(n-r+l-1))continue;
			ans=max(x+y-n,ans);
		}
		printf("%lld\n",ans);
	// }
}

#include<bits/stdc++.h>
using namespace std;typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pii;
const int inf = 0x3f3f3f3f,oo = inf;
#define pi 3.14159265358979323846
#define IL inline
#define RG register
#define rep(i,a,b) for(RG int i=(a);i<int(b);++i)
#define Rep(i,a,b) for(RG int i=(a);i<=(b);++i)
#define Dep(i,a,b) for(RG int i=(a);i>=(b);--i)
#define pc putchar
#define gc getchar
IL ll read(){
    RG ll lson=0;char f=0;RG char c=gc();
    for(;!isdigit(c);c=gc())f|=(c=='-');
    for(;isdigit(c);c=gc())lson=(lson<<1)+(lson<<3)+(c^48);
    return f?-lson:lson;
}
IL void write(ll lson){if(lson<0)lson=-lson,pc('-');if(lson>=10)write(lson/10);pc(lson%10+'0');}
IL void writeln(ll lson){write(lson);puts("");}
IL void writeln(ll lson,char c,ll rson){write(lson);pc(c);writeln(rson);}
IL void writeln(ll lson,char c,ll rson,char d,ll z){write(lson);pc(c);write(rson);pc(d);writeln(z);}
#define debug(lson) printf(#lson" = %d\n",lson);
#define rd() read()
#define rdb() readdb()
#define pb push_back
#define mp make_pair
#define y1 ____y1
#define union _union
#define int ll
int n,l,r,k,p,X;
ll up(ll a,ll b){
	return a / b + (!(a % b == 0));
}
ll down(ll a,ll b){
	return a / b;
}
signed main(){
	n = rd(),l = rd(),r = rd(),k = rd();
	int p = (r - l + 1 + n) % n;
	int ans=-1+n;
	for(ll i=k,j,alb,L,R;i;i=j-1){
		j = k/(k/i+1)+1;
		alb = k/i;
		//j to i
		L = n;
		L = max(L,j);
		L = max(L,up(k-2*p,alb));
//另总人数为limit
//另x = k % limit
//p <= k-k/limit*limit <= 2*p
//得到limit的范围
//2(n-p) <= limit - (k-k/limit*limit) <= 2n
//2(n-p) <= limit - (k-k/limit*limit) <= 2n
//2*(n-p) <= limit - k + k/limit*limit
//2*(n-p) + k <= (k/limit+1)*limit
		R = 2 * n;
		R = min(R,i);
		R = min(R,down(k-p,alb));
		R = min(R,down(2*(n-p)+k+1,alb+1));
	//一种情况是最后一个人应该拿2个但是拿了1个
		if(L<=R) ans=max(ans,R);
	}
	if(p<=k&&k<=2*p){
		ans = max(ans,n + min(k-p,p-1) + n - p + 1);
	}
	writeln(ans-n);
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll n,l,r,m,s,up,x,y;

void exgcd(ll a,ll b,ll& x,ll &y) {
	if (!b) {x=1; y=0; return;}
	exgcd(b,a%b,y,x);
	y-=x*(a/b);
}

ll l1,r1,l2,r2,ans=-1;
int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&m);
	s=(r-l+n)%n+1; up=m-s;
	if (m<s) return puts("-1"),0;

	if (m-s<=s) ans=max(ans,m-s+n-s);
	for (ll i=n;i<=min(2*n,up);i=up/(up/i)+1) {
		ll k=up/i,right=up-k*n;
		if (right==0) {ans=max(ans,0ll); continue;}
		exgcd(k+1,k,x,y);
		x=x*right; y=y*right;
		l1=(x-s)%k==0 ? (x-s)/k : (x-s)/k+1;
		r1=x/k;
		//printf("%lld %lld\n",l1,r1);
		l2=y%(k+1)==0 ? -y/(k+1) : -y/(k+1)+1;
		r2=(n-s-y)/(k+1);
		//printf("%lld %lld\n",l2,r2);
		if (l2>r1 || l1>r2 || l1>r1 || l2>r2) continue;
		ans=max(ans,i-n);
	}

	m++; up=m-s;
	if (m-s<=s) ans=max(ans,m-s+n-s);
	for (ll i=n;i<=min(2*n,up);i=up/(up/i)+1) {
		ll k=up/i,right=up-k*n;
		if (right==0) {ans=max(ans,0ll); continue;}
		exgcd(k+1,k,x,y);
		x=x*right; y=y*right;
		l1=(x-s)%k==0 ? (x-s)/k : (x-s)/k+1;
		r1=x%k==0 ? x/k-1 : x/k;
		l2=y%(k+1)==0 ? -y/(k+1) : -y/(k+1)+1;
		r2=(n-s-y)/(k+1);
		if (l2>r1 || l1>r2 || l1>r1 || l2>r2) continue;
		ans=max(ans,i-n);
	}
	printf("%lld\n",ans);
	return 0;
}

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define y0 y_0
#define y1 y_1
#define yn y_n
#include <assert.h>
#include <algorithm>
#include <vector>
using namespace std;
const double Infd=1e18;

long long solve(long long n,long long l,long long r,long long k,bool f){
	long long cnt=(r+n-l)%n+1;
	if(f)k++;
	assert(cnt>0&&k>0);
	k-=cnt;
	if(k<0)return -1;
	// #1
	// k >= 0, k = q * (sc + n) + sclr
	long long rem=n-cnt,sq=sqrt(k);
	if(sq>n){
		for(int sc=n;sc>=0;sc--){
			int sclr=k%(sc+n);
			if(sclr<=sc&&sclr<=cnt&&sclr+rem>=sc){
				if(f&&sc==0)continue;
				return sc;
			}
		}
		return -1;
	}
	// #2
	long long res=-1;
	// k >= 0, k = sclr
	long long sc=n-(cnt-k);
	if(k<=sc&&k<=cnt&&k+rem>=sc)res=max(res,sc);
	// k >= 0, k = qx + y
	for(int q=1;q<=sq+1;q++){
		k-=n;
		if(k<0)break;
		long long x0=k,y0=q*k-k,dx=1,dy=-q;
		assert(dx>0&&dy<0);
		double l=-Infd,r=Infd;
		l=max(l,-double(x0)/dx),r=min(r,-double(y0)/dy); // x >= 0, y >= 0
		r=min(r,double(n-x0)/dx),l=max(l,double(y0-x0)/(dx-dy)); // x <= n, y <= x
		l=max(l,double(cnt-y0)/dy),r=min(r,double(y0-x0+rem)/(dx-dy)); // y <= cnt, x <= y + rem
		long long il=(long long)ceil(l),ir=(long long)floor(r);
		if(il>ir)return -1;
		res=max(res,x0+dx*ir);
	}
	return (f&&res==0)?-1:res;
}

long long n,l,r,k;

int main(){
	scanf("%lld %lld %lld %lld",&n,&l,&r,&k);
	printf("%lld\n",max(solve(n,l,r,k,false),solve(n,l,r,k,true)));
	return 0;
}

#include<bits/stdc++.h>

typedef long long ll;

ll divide(ll a, ll b){
    return a / b - ((a ^ b) < 0 && a % b);
}

ll solvele(ll a, ll b){
    return divide(b, a);
}

ll solvege(ll a, ll b){
    return divide(b + a - 1, a);
}

int main(){
    ll n, l, r, k;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    ll x = r - l + 1;
    if (x < 0){
        x += n;
    }
    if (x == n){
        ll max = -1;
        for (ll i = 1; i * i <= k; ++ i){
            if (k % i == 0){
                if (i <= n << 1){
                    max = std::max(max, i - n);
                }
                if (k / i <= n << 1){
                    max = std::max(max, k / i - n);
                }
            }
            if ((k + 1) % i == 0){
                if (n + 1 <= i && i <= n << 1){
                    max = std::max(max, i - n);
                }
                if (n + 1 <= k / i && k / i <= n << 1){
                    max = std::max(max, k / i - n);
                }
            }
        }
        printf("%lld\n", max);
        return 0;
    }
    ll ans = -1;
    for (ll i = 1, j; i <= k; i = j + 1){
        ll t = k / i;
        j = k / t;
        ll min = std::max(0ll, i - n), max = j - n;
        max = std::min(max, solvele(t, k - t * n - x));
        min = std::max(min, solvege(t, k - t * n - 2 * x));
        max = std::min(max, solvele(t + 1, k - t * n - x + n - x));
        min = std::max(min, solvege(t + 1, k - t * n - x));
        if (min <= max){
            ans = std::max(ans, max);
        }
        min = std::max(0ll, i - n), max = j - n;
        max = std::min(max, solvele(t, k - t * n - x));
        min = std::max(min, solvege(t, k - t * n - 2 * x + 1));
        max = std::min(max, solvele(t + 1, k - t * n - x + n - x + 1));
        min = std::max(min, solvege(t + 1, k - t * n - x + 1));
        if (min <= max){
            ans = std::max(ans, max);
        }
    }
    ll min = std::max(0ll, k - n + 1), max = n;
    if (0 <= k - x && k - x <= x){
        max = std::min(max, solvele(1, k - x + n - x));
        min = std::max(min, solvege(1, k - x));
        if (min <= max){
            ans = std::max(ans, max);
        }
    }
    min = std::max(0ll, k - n + 1), max = n;
    if (1 <= k - x + 1 && k - x + 1 <= x){
        max = std::min(max, solvele(1, k - x + n - x));
        min = std::max(min, solvege(1, k - x + 1));
        if (min <= max){
            ans = std::max(ans, max);
        }
    }
    printf("%lld\n", ans);
    return 0;
}

#include <bits/stdc++.h>
#define mp make_pair
#define X first
#define Y second
#define pii pair<ll,ll>
#define x1 dlfjl
#define x2 dkfj
#define x3 dflgkg
#define y1 dskgj
#define y2 dskfj
#define y3 dfhgdh
#define SQ 320
#define PI 3.14159265359
#define MOD 1000000007
#define MAXN 1000005
typedef long long ll;
using namespace std;
ll i,j,k,z,q,timer,x,y,n,m, cnt, even, flag, x1,y1,x2,y2, boom,r,c;
vector<pii> f, f1;
ll solve(ll n, ll l, ll r, ll k, ll id) {
    ll C1 = 2*(r-l+1)-k;
    ll C2 = k - (r-l+1);
    ll m1 = -C1/(2*n) - 5;
    ll m2 = C2/n - 5;
    //cout << C1 << " " << C2 << endl;
    while (2*m1*n + C1 < 0)
        m1++;
    while (C2 - m2*n - n >= 0)
        m2++;
    //cout << m1 << " " << m2 << endl;
    if (m1 > m2) {
        return -1;
    }

    ll ans = -1;
    if (m1 == 0) {
        ll diff = k-(r-l+1);
        if (diff >= id && diff <= r-l+1)
            ans = diff + n-(r-l+1);
        m1++;
    }
    //cout << m1 << " " << m2 << endl;
    for (ll i = m1; i <= min(m2, m1+400000); i++) {
        ll T = C2 - i*n;
        ll x, y;
        ll K = 0;
        for (int j = 0; j < 40; j++) {
            K += (1LL<<j);
            if (T/i - K - T % i - i * K <= n-(r-l+1))
                K -= (1LL<<j);
        }
        K++;
        y = T/i-K-T%i-i*K;
        x = (T - y*i)/(i+1);
        //cout << x << " " << y << endl;
        if (x >= id && x <= r-l+1 && y >= 0 && y <= n-(r-l+1))
            ans = max(ans, x+y);
    }

    return ans;
}
int main() {
    //freopen("input.txt", "r", stdin);
    ll n, l, r, k;
    cin >> n >> l >> r >> k;
    if (l > r) {
        r += n;
    }
    ll ans1 = solve(n,l,r,k,0);
    ll ans2 = solve(n,l,r,k+1,1);
    //cout << ans1 << " " << ans2 << endl;
    cout << max(ans1, ans2) << endl;
    return 0;
}

/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return x?8*sizeof(int)-__builtin_clz(x):0; }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskD {
public:
void solve(istream& cin, ostream& cout) {
    ll N, L, R, K;
    cin >> N >> L >> R >> K;
    ll Q = (N+R-L+1)%N;
    if (Q == 0) Q = N;

    if (K < Q) {
        cout << "-1\n";
        return;
    }

    ll ans = -1;

    if (K <= 2*Q) {
        cout << min(N, K-Q + 1 + (N-Q)) << endl;
        return;
    }

    for (ll rev = 1; rev <= 1000000; ++rev) {
        for (ll take : {(K - 2*Q) / rev, (K-Q)/rev}) {
            ll s = take - N;
            if (s < 0) continue;
            if (s > N) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0) continue;
            if (left > Q) continue;
            if (left > s) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    for (ll take = 1; take <= 1000000; ++take) {
        if (take < N) continue;
        if (take > 2 * N) continue;
        ll s = take - N;
        for (ll rev = (K - 2*Q) / take - 1; rev <= (K-Q) / take + 1; ++rev) {
            if (rev <= 0) continue;
            ll left = (K - Q) - rev * take;
            if (left < 0) continue;
            if (left > Q) continue;
            if (left > s) continue;
            if (min(Q, left + 1) + (N - Q) < s) continue;
            ans = max(ans, s);
        }
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskD solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}

//http://codeforces.com/contest/1064
//http://codeforces.com/contest/1064/problem/F
#include <iostream>

using namespace std;

long long n, l, r, k;

inline bool check(long long x)
{
    if(x > n || x < 0) return false;

    long long x1min, x1max, ost;
    ost = k % (n + x);
    if(ost == 0) ost += x;
    x1min = x - min(n - r, x) - 1;
    x1max = min(r, x);
    if(x1min <= ost && ost <= x1max){
        cout << x << endl;
        return true;
    }
    return false;
}

int main()
{
    cin >> n >> l >> r >> k;
    r = (r + n - l) % n + 1;
    k -= r;
    if(k < 0){
        cout << -1 << endl;
        return 0;
    }

    if(check(n - r + k + 1)) return 0;
    if(check(n - r + k)) return 0;

    if(n < 1e7){
        for(long long y = n; y >= 0; --y)
            if(check(y)) return 0;
        cout << -1 << endl;
        return 0;
    }

    for(long long z = 1, k1 = k; k1 >= n; ++z){
        k1 -= n;

        long long y2 = min(n - r, k1 / z); // y2max
        long long y1 = min(r, (k1 + 1 - z * y2) / (z + 1));
        if(check(y1 + y2)) return 0;
    }
    cout << -1 << endl;

    return 0;
}

/**************************************************************
    Problem: ????
    User: Big_Red_Dates
    Language: GNU_C++11
    Result: Accepted
    Time:0 ms
    Memory:0 kb
    length:0 kb
    score: inf
****************************************************************/
//CLOCKS_PER_SEC
using namespace std;
#include<bitset>
#include<deque>
#include<stdint.h>
#include<set>
#include<stack>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<iomanip>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<ctime>
#include<map>
#define sqr(x) (x)*(x)
#define sort stable_sort
#define ll long long
#define mk make_pair
#define pb push_back
#define in insert
#define mtr(x,y,z) mk(mk(x,y),z)
#define fi first
#define se second
#define lch(x) ((x)<<1)
#define rch(x) (((x)<<1)|1)
#define all(x) (x).begin(),(x).end()
#define titose CLOCKS_PER_SEC
#define fpi(x) freopen(x,"r",stdin);
#define fpo(x) freopen(x,"w",stdout);
#define fprio fpi("in.txt");fpo("out.txt");
#define fast ios_base::sync_with_stdio(false);
inline void read(int &x){int v=0,f=1;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=v*10+c-'0';while (isdigit(c=getchar())) v=v*10+c-'0';x=v*f;}
inline void read(ll &x){ll v=0ll,f=1ll;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=v*10+c-'0';while (isdigit(c=getchar())) v=v*10+c-'0';x=v*f;}
inline void readc(char &x){char c;while ((c=getchar())==' ');x=c;}
inline void writes(string s){puts(s.c_str());}
inline void writeln(){writes("");}
inline void writei(int x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
inline void writell(ll x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
/*
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)
#pragma GCC optimize(5)
#pragma GCC optimize(6)
#pragma GCC optimize(7)
#pragma GCC optimize(8)
#pragma GCC optimize(9)
*/
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define vl vector<ll>
#define si set<int>
#define sl set<ll>
#define mii map<int,int>
#define mll map<ll,ll>
#define msi map<string,int>
#define msl map<string,ll>
#define piii pair<int,pii >
#define piipi pair<pii,int>
#define plll pair<ll,pll >
#define pllpl pair<pll,ll>
#define pqi priority_queue<int>
#define pql priority_queue<ll>
#define npqi priority_queue<int,vector<int>,greater<int> >
#define npql priority_queue<ll,vector<ll>,greater<ll> >
#define forup(i,csc,lys) for ((i)=(csc);(i)<=(lys);(i)++)
#define fordo(i,csc,lys) for ((i)=(csc);(i)>=(lys);(i)--)
#define rep(i,x) forup ((i),1,(x))
#define repd(i,x) fordo ((i),(x),1)
#define itr iterator
#define lyscsc(itcalc,c) for(__typeof((c).begin()) itcalc=(c).begin();itcalc!=(c).end();itcalc++)
#define NO {cout<<"-1";return 0;}
#define YES {cout<<"YES";return 0;}
#define y0 y000000000000000000000000000
#define y1 y111111111111111111111111111
#define j0 j000000000000000000000000000
#define j1 j111111111111111111111111111
#define cl0(a) memset((a),(0),(sizeof((a))))
#define clz(a) memset((a),(0x16),(sizeof((a))))
#define clf(a) memset((a),(-(0x16)),(sizeof((a))))
#define inf 0x3bbbbbbb
#define lnf 0x1bbbbbbbbbbbbbbbll
#define sqrt divi
#define p2(i) (1ll<<(i))
#define readi read
#define readll read
/*************************************************/
ll n,m,i,j,l,r,k,b=250000,ans=-1;
int main()
{
	cin>>n>>l>>r>>k;
	l=(r+n-l+1)%n;
	if (n<=b)
	{
		for (i=0;i<=n;i++)
		{
			ll t=k%(n+i);
			if (t>=l+min(l,max(0ll,i-(n-l)-1))&&t<=l+min(l,i))
			{
				ans=max(ans,i);
			}
		}
	}
	else
	{
		for (i=0;i*n<=k;i++)
		{
			ll p=(k-l-l-(i-1)*n+1)/(i+1);
			ll y=k-i*(n+p)-l;
			if (y<0)
			{
				if (i==0) continue;
				ll dis=(-y-1)/i+1;
				y+=i*dis;
				p-=dis;
			}
			if (p>n)
			{
				p=n;
			}
//			cerr<<i<<' '<<p<<endl;
			ll t=k%(n+p);
			if (t>=l+min(l,max(0ll,p-(n-l)-1))&&t<=l+min(l,p))
			{
				ans=max(ans,p);
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}

#include <iostream>
#include <stdint.h>
#include <algorithm>

using namespace std;
using int64 = int64_t;

int64 Solve(int64 n, int64 xl, int64 k_xl) {
    int64 c_final = -1;
    int64 m_max = k_xl / n;
    int64 m_min = max(k_xl - xl, 0ll) / (2 * n);

    // cout << n << ' ' << m_max << ' ' << m_min << '\n';

    if (m_min == 0) {
        if (k_xl <= xl) {
            c_final = n + n - xl + k_xl;
            if (k_xl < xl)
                c_final += 1;
            return c_final;
        } else {
            m_min += 1;
        }
    }

    if (n < m_max - m_min)
    {
        for (int64 c = 2 * n; c >= n; --c) {
            int64 x_xl = k_xl % c;
            if (x_xl <= xl) {
                c_final = c;
                break;
            }
        }
    } else {
        for (int m = m_min; m <= m_max; ++m) {
            int64 x_xl = max(k_xl % m, k_xl - m*2*n);
            if (x_xl <= xl) {
                c_final = k_xl / m;
                break;
            }
        }
    }
    return c_final;
}

int main() {
    int64 n, l, r, k;
    cin >> n >> l >> r >> k;

    int64 xl = r >= l ? r - l + 1 : r - l + n + 1;
    xl %= n;

    int64 k_xl = k - xl;
    if (k_xl < 0) {
        cout << -1 << endl;
        return 0;
    }

    // cout << n << ' ' << xl << ' ' << k_xl << '\n';
    int64 c = Solve(n, xl, k_xl);

    if (xl == 0) {
        int64 c2 = Solve(n, xl, k_xl + 1);
        if (c2 > n && c2 > c)
            c = c2;
    }

    if (c >= n)
        c -= n;

    cout << c << endl;

    return 0;
}

#include <bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;

long long n, l, r, k;
const int rlimit = 1e6;
long long ans = -1;
int main()
{
	scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
	long long mu = (r - l + n) % n + 1;
	if (k >= mu && k <= 2 * mu)
	{
		ans = (n - mu) + (k - mu);
		if (ans < n)
		{
			ans++;
		}
	}
	if (ans < 0)
	{
		long long tk = k - mu;
		if (n < k / n)
		{
			for (int i = n; i >= 0 && ans < 0; i--)
			{
				long long b = (tk + 1) % (n + i);
				if (b <= i)
				{
					if(i > ans)
						ans = i;
				//	break;
				}
				b = tk % (n + i);
				if (b <= i && b)
				{
					if(i > ans)
						ans = i;
					//break;
				}
			}
		}
		else
		{
			long long kn = k / n;
			for (int i = 1; i <= kn && ans < 0; i++)
			{
				long long ttk = tk - n * i;
				if (ttk + 1 < 0)
					break;

				if (ttk + 1 >= 0)
				{
					long long tmp = (ttk + 1) / i;
					if ((ttk + 1) % i == 0)
						tmp--;
					long long x = min((n - mu + ttk + 1) / (i + 1), tmp);

					if (ttk > x*(i + 1))
						x = 0;
					if (x && x > ans)
						ans = x;
				}
				if (ttk >= 0)
				{
					long long x = min((n - mu + ttk) / (i + 1), ttk / i);
					if (ttk > x*(i + 1))
						x = 0;
					if (x && x > ans)
						ans = x;
					else if (ttk == 0 && ans < 0)
					{
						ans = 0;
					}
				}
			}
		}
	}
	printf("%d\n", ans);
}

#include<bits/stdc++.h>
#define max(a,b) (((a)>(b))?(a):(b))
#define min(a,b) (((a)<(b))?(a):(b))
#define LL long long
using namespace std;
template<typename T>void read(T &x){
	x=0;int f=1;
	char c=getchar();
	for(;!isdigit(c);c=getchar()) if (c=='-') f=-1;
	for(;isdigit(c);c=getchar()) x=x*10+c-48;
	x*=f;
}
LL n,l,r,k;
LL ans=-1;
int main(){
	read(n);read(l);read(r);read(k);
	LL len=r-l+1;
	if(len<0) len+=n;
	if(n<=5000){
		for(LL i=0;i<=len-1;++i)
			for(LL j=0;j<=n-len;++j){
				//r==1
				LL kk=k-1;
				kk%=i+j+n;
				kk++;
				if(kk==i+len) ans=max(ans,i+j);
				//r==2
				kk=k-1;kk%=i+j+1+n;kk++;
				if(kk==i+len||kk==i+len+1) ans=max(ans,i+j+1);
			}
	}
	else{
		LL lim=k/n;
		//c==0
		if(k<=2*len||k>=len) ans=max(ans,n-(k-len+1));
		for(LL c=1;c<=lim;++c){
			LL pr=k/c;
			if(pr>2*n) continue;
			LL rst=k%c;
			LL mx=min(pr-n,len);
			LL mi=max(0,pr-2*(n-len)-1);
			if(rst>r-l+1+mx) continue;
			if(rst<r-l+1-mi) continue;
			ans=max(ans,pr-n);
		}
	}
	cout<<ans<<endl;
	return 0;
}

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <tuple>
#include <iterator>
#include <cmath>

using namespace std;

const int THR = 5000;

int main()
{
    //freopen("in", "r", stdin);
    //freopen("out", "w", stdout);

    long long n, l, r, k;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);

    long long d = (r - l + 1 + n) % n;

    if(k < d)
    {
        puts("-1");
        return 0;
    }

    long long res = -1;
    if(n < THR)
    {
        for(long long i = 0; i <= d; i++)
        {
            for(long long j = 0; j <= (n - d); j++)
            {
                long long t = k - (d + i);
                if(t == 0 || i > 0 && t == -1)
                {
                    res = max(res, i + j);
                    continue;
                }

                long long q = t / (n + i + j);
                long long t2 = t - q * (n + i + j);
                if(t2 == 0 || i > 0 && t2 == -1)
                {
                    res = max(res, i + j);
                    continue;
                }

                long long t3 = t - (q + 1) * (n + i + j);
                if(t3 == 0 || i > 0 && t3 == -1)
                {
                    res = max(res, i + j);
                    continue;
                }
            }
        }
    }
    else
    {
        long long s, g;
        s = max(0LL, (k / 2 - d + n - 1) / n);
        g = max(s, (k - d) / n);

        for(long long i = s; i <= g; i++)
        {
            if(k < d + n * i)
                break;

            if(k > 2 * (d + n * i))
                continue;

            if(i == 0)
            {
                res = max(res, min(d, k + 1 - d) + n - d);
                continue;
            }
            {
                long long t = k - (d + n * i);

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(r1 == 0)
                            res = max(res, n - d + q);
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(r1 == 0)
                            res = max(res, q);
                    }
                }
            }
            {
                long long t = k + 1 - (d + n * i);
                t -= i + 1;

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(r1 == 0)
                            res = max(res, n - d + q + 1);
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(r1 == 0)
                            res = max(res, q + 1);
                    }
                }
            }
        }
    }

    printf("%lld\n", res);
    return 0;
}

#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
#include<set>
#include<vector>
#define int long long
#define PII pair<int,int>
#define pb push_back
#define ep emplace_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
inline int read(){
	int x=0,f=1;char c=getchar();
	while(c<'0'||c>'9'){ if(c=='-') f=-1; c=getchar();}
	while(c>='0'&&c<='9'){x=(x<<3)+(x<<1)+(c^48);c=getchar();}
	return f==1?x:-x;
}
inline void print(int x){
	if(x<0) putchar('-'),x=~x+1;
	if(x>=10) print(x/10);
	putchar((x%10)|48);
}
int n;
int l,r,k;
signed main(){
	n=read();
	l=read(),r=read(),k=read();
	if(k<r-l+1){
		printf("-1\n");
	}
	else {
		k-=r-l+1;
		if(k<=r-l+1) printf("%lld\n",k+(n-(r-l+1))+1);
		else{
			if(k<n){
				printf("-1\n");
			}
			else{
				int t=k/n,lf=k%n;
				if(t>=1e5){
					int ans=0;
					for(int i=1;i<=n-(r-l+1);++i){
						if(k%(n+i)<=i&&k%(n+i)<=(r-l+1)) ans=i;
					}
					for(int i=n-(r-l+1)+1;i<=n;++i){
						int minn=i-(n-(r-l+1));
						if(k%(n+i)>=minn&&k%(n+i)<=(r-l+1)) ans=i;
					}
					print(ans);
				}
				else{
					int ans=0;
					for(int p=0;p<=t;++p){
						int turn=t-p;
						if(lf>turn*n+r-l+1) break ;

						int x=lf/turn;
						int y=lf%turn;
						if(x>n-(r-l+1)){
							while(y<x-(n-(r-l+1))){
								--x,y+=turn;
							}
							if(y<=r-l+1) ans=x;
						}
						else {
							if(y<=x&&y<=r-l+1) ans=x;
						}
						lf+=n;
					}
					print(ans);
				}
			}
		}
	}
	return 0;
}

#include <iostream>
#include <ios>
#include <cstdint>
#include <vector>
#include <string>
#include <random>
#include <utility>
#include <ctime>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <complex>
#include <queue>
#include <cstdio>
#include <iomanip>

using ul = std::uint32_t;
using li = std::int32_t;
using ull = std::uint64_t;
using ll = std::int64_t;
using vul = std::vector<ul>;
using vvul = std::vector<vul>;
using vb = std::vector<bool>;
using vvb = std::vector<vb>;
using vvvb = std::vector<vvb>;
using vull = std::vector<ull>;
using vvull = std::vector<vull>;
using vli = std::vector<li>;
using vll = std::vector<ll>;
using pulul = std::pair<ul, ul>;
using vpulul = std::vector<pulul>;
using lf = double;
using vlf = std::vector<lf>;

ll n, k, l, r;
std::mt19937 rands;

ll up(ll a, ll b)
{
	return a < 0 ? a / b : (a + b - 1) / b;
}

ll low(ll a, ll b)
{
	return a < 0 ? (a - b + 1) / b : a / b;
}

int main()
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::cin >> n >> l >> r >> k;
	r = (r + n - l + 1) % n;
	if (!r) {
		r = n;
	}
	if (n < k / n) {
		for (ll t = n; t; --t) {
			ll b = k % (n + t);
			if (!b) {
				b = n + t;
			}
			if (b <= 2 * r && b <= t + r && b >= r && b >= t + 2 * r - n - 1) {
				std::cout << t << std::endl;
				return 0;
			}
		}
		std::cout << "-1" << std::endl;
		return 0;
	} else {
		ll ans = -1;
		for (ll a = 0; a * n < k; ++a) {
			if (!a) {
				if (k <= 2 * r && k >= r) {
					ll s = std::max(k - r, ll(1));
					ll t = std::min(k - 2 * r + n + 1, n);
					if (t >= s) {
						ans = std::max(ans, t);
					}
				}
				continue;
			}
			ll s = std::max(std::max(up(k - a * n - 2 * r, a), up(k - a * n - r, a + 1)), ll(1));
			ll t = std::min(std::min(low(k - a * n - r, a), low(k - a * n + n - 2 * r + 1, a + 1)), n);
			if (t >= s) {
				ans = std::max(ans, t);
			}
		}
		std::cout << ans << std::endl;
	}
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

using ll = long long;
ll n, l, r, k;
ll d;
ll last;

ll doT(ll p) {
   ll lb = last;
   ll ub = n;
   ll ans = -1;
   while (lb <= ub) {
      ll mid = (ub -lb) / 2 + lb;
      ll sb = mid;
      ll sa = min(sb, n - d);
      sb -= sa;
      if (sb < last) {
         sb++;
         sa--;
      }

      ll from = p * (n + mid) + d + sb;

      sb = min(mid, d);
      sa = mid - sb;
      ll to = p * (n + mid) + d + sb;

      if (from > k) {
         ub = mid - 1;
      } else if (to < k) {
         lb = mid + 1;
      } else {
         lb = mid + 1;
         ans = max(ans, mid);
      }
   }
   return ans;
}

ll doSum(ll p) {
   ll lb = last;
   ll ub = k;
   ll max_sa = min(p - last, n - d);
   ll min_sb = p - max_sa;
   ll max_sb = min(p, d);
   ll min_sa = p - max_sb;
   while (lb <= ub) {
      ll mid = (ub - lb) / 2 + lb;
      ll from = mid * (n + p) + d + min_sb;
      ll to = mid * (n + p) + d + max_sb;

      if (from > k) {
         ub = mid - 1;
      } else if (to < k) {
         lb = mid + 1;
      } else {
         return p;
      }
   }

   return -1;
}

int main() {
   ios::sync_with_stdio(false);
   cin >> n >> l >> r >> k;
   r--; l--;
   l = (l - 1 + n) % n;
   d = (r - l + n) % n;

   ll ans = -1;
   for (ll p = 0; p * p <= k; p++) {
      ans = max(ans, doT(p));
      ans = max(ans, doSum(p));
   }
   if (d) {
      k++;
      last = 1;
      for (ll p = 0; p * p <= k; p++) {
         ans = max(ans, doT(p));
         ans = max(ans, doSum(p));
      }
   }

   cout << ans << endl;
}

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

int main() {
	long long n, l, r, k;
	scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
	long long a = (r + n - l + 1) % n;
	if (n == 1) {
		printf("1\n");
		return 0;
	}
	if (k < a) {
		printf("-1");
		return 0;
	}
	long long ans = -1;
	if (k - a >= 0 && k - a <= a) ans = max(ans, k - a + n - a);
	for (long long l, r, i = 1; i <= k; i = r + 1) {
		l = i;
		r = k / (k / l);
		long long m = k / l;
		if (l - n > n) continue;
		long long bot = max(ceil((double)((k - a) / m - n - (k - a) % m - n + a) / (m + 1)), ceil((double)(-(k - a) % m) / m));
		long long top = min(floor((double)((k - a) / m - n - (k - a) % m) / (m + 1)), floor((double)(a - (k - a) % m) / m));
		if (bot <= top) ans = max(ans, (k - a) / m - bot - n);
	}
	k++;
	if (k - a >= 1 && k - a <= a) ans = max(ans, k - a + n - a);
	for (long long l, r, i = 1; i <= k; i = r + 1) {
		l = i;
		r = k / (k / l);
		long long m = k / l;
		if (l - n > n) continue;
		long long bot = max(ceil((double)((k - a) / m - n - (k - a) % m - n + a) / (m + 1)), ceil((double)(1 - (k - a) % m) / m));
		bot = max(bot, (k - a) / m - r);
		long long top = min(floor((double)((k - a) / m - n - (k - a) % m) / (m + 1)), floor((double)(a - (k - a) % m) / m));
		top = min(top, (k - a) / m - l);
		if (bot <= top) ans = max(ans, (k - a) / m - bot - n);
	}
	printf("%lld", ans);
	return 0;
}

#include <bits/stdc++.h>
using namespace std;

long long way1(long long LHS, long long n, long long pmin, long long pmax, long long qmin, long long qmax) {
    // Way 1: Ã¶¾Ùp
    long long p;
    long long ret = -1;
    for (p = pmin; p <= pmax; p++) {
        long long q = LHS % (n + p);
        if (q >= qmin && q <= qmax && q <= p && q >= p + qmax - n) {
            ret = max(ret, p);
        }
    }
    return ret;
    // ¸´ÔÓ¶È£ºO(pmax)=O(n)
}

long long way2(long long LHS, long long n, long long pmin, long long pmax, long long qmin, long long qmax) {
    // Way2: Ã¶¾Ùt
    long long ret = -1;
    for (long long t = (LHS - qmax + n + pmax - 1) / (n + pmax); t <= (LHS - qmin) / (n + pmin); t++) {
        if (t == 0) {
            long long p;
            long long q = LHS;
            if (q < qmin || q > qmax) {
                continue;
            }
            long long nowpmin, nowpmax;
            nowpmin = max(pmin, q);
            nowpmax = min(pmax, q + pmax - qmax);
            if (nowpmin <= nowpmax) {
                p = nowpmax;
                ret = max(ret, p);
            }
        } else {
            long long p = LHS / t - n;
            long long q = LHS % t; // ×îÐ¡µÄq
            // ³õ²½µ÷Õû
            long long u;
            long long umax = 0, umin = p;
            // p·¶Î§ÏÞÖÆ
            // q·¶Î§ÏÞÖÆ
            umax = min(min(p - pmin, (qmax - q) / t), (p-q) / (t+1));
            umin = max(max(p - pmax, (qmin - q + t - 1) / t), (p - pmax + qmax - q + t) / (t + 1));
            // Ó¦ÓÃ
            if (umin <= umax) {
                u = umin;
                p -= u;
                q += t * u;
                ret = max(ret, p);
            }
        }
    }
    return ret;
    // ¸´ÔÓ¶È£ºO(LHS/n)
}

int main() {
    long long n, l, r, k;
    cin >> n >> l >> r >> k;
    long long d = (r+n-l) % n + 1;
    long long LHS = k-d;
    if (n < LHS / n) {
        cout << max(way1(LHS, n, 0, n, 0, d), way1(LHS+1, n, 1, n, 1, d)) << endl;
    } else {
        cout << max(way2(LHS, n, 0, n, 0, d), way2(LHS+1, n, 1, n, 1, d)) << endl;
    }

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define sqr(x) ((x)*(x))
#define mp make_pair
#define PI pair<ll,ll>
inline char gc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
#define gc getchar
inline ll read(){
	ll x = 0; char ch = gc(); bool positive = 1;
	for (; !isdigit(ch); ch = gc())	if (ch == '-')	positive = 0;
	for (; isdigit(ch); ch = gc())	x = x * 10 + ch - '0';
	return positive ? x : -x;
}
inline void write(ll a){
    if(a<0){
    	a=-a; putchar('-');
	}
    if(a>=10)write(a/10);
    putchar('0'+a%10);
}
inline void wri(ll a){write(a); putchar(' ');}
inline void writeln(ll a){write(a); puts("");}
const ll inf=1e18;;
ll n,l,r,k,t;
PI jiao(PI x,PI y){
	return mp(max(x.first,y.first),min(x.second,y.second));
}
inline ll chu(ll x,ll y){
	if(y==0)return -inf;
	return x%y==0?x/y:x/y+1;
}
void solve(ll l,ll r,int id){
	ll ans=-1;
	for(ll i=n,pos,jb,L,R;i<=2*n;i=pos+1){
		jb=k/i; pos=jb?k/jb:inf;
		if(id&2){
			L=chu(k-2*t,jb); if(jb==0&&k>2*t)L=inf;
			//k-i*jb<=2*t
		}else{
			L=chu(k-t+n,jb+1);
			//k-i*jb<=t+i-n
		}
		if(id&1){
			R=(k+2*n+1-2*t)/(jb+1); //k-i*jb>=2*t-1+(i-n) k-n*jb-i*jb>=2*t-1+i-n
		}else{
			R=jb?(k-t)/jb:inf; if(jb==0&&k<t)R=-inf;
			//k-i*jb>=t
		}
		PI T=jiao(jiao(mp(l+n,r+n),mp(L,R)),mp(i,pos));
		//if(l<=2&&r>=2)cout<<id<<" "<<T.first<<" "<<T.second<<" "<<k-jb*n+n+1-2*t<<" "<<jb<<" "<<i<<" "<<pos<<" "<<L<<" "<<R<<" "<<l<<" "<<r<<endl;
		if(T.first<=T.second)ans=max(ans,T.second);
	}
	if(ans>=0){
		cout<<ans-n<<endl; exit(0);
	}
}
signed main(){
	n=read(); l=read(); r=read(); k=read();
	t=(r-l+n)%n+1;
	if(t==n){
		ll ans=-1;
		for(ll i=1;i*i<=k;i++)if(k%i==0){
			if(i>=n&&i<=2*n)ans=max(ans,i-n);
			if(k/i>=n&&k/i<=2*n)ans=max(ans,k/i-n);
		}
		for(ll i=1;i*i<=k+1;i++)if((k+1)%i==0){
			if(i>n&&i<=2*n)ans=max(ans,i-n);
			if(k/i>n&&k/i<=2*n)ans=max(ans,k/i-n);
		}
		cout<<ans<<endl; return 0;
	}
	if(t<=(n-(t-1))){
		solve(n-t+1,n,3);
		solve(t,n-t+1,2);
		solve(0,t,0);
	}else{
		solve(t,n,3);
		solve(n-t+1,t,1);
		solve(0,n-t+1,0);
	}
	puts("-1");
}
/*
	for(ll i=n;i>=0&&i>n-X;i--){
		ll zs=k%(n+i)?k%(n+i):n+i;// if(i==3)cout<<zs<<" "<<i-(n-(t-1))<<" "<<endl;
		if(zs>max((ll)0,i-(n-(t-1)))+t-1&&zs<=min(t,i)+t){
			cout<<i<<endl; return 0;
		}
	}
枚举i个人甜
t恰好吃完了k个
t<=k%(n+i)<=2*t
t n-(t-1)
n%(k+i)=n-(k+i)*jb
k-(n+i)*jb<=2*t
(n-k*jb-2*t)/jb<=i
k-(n+i)*jb<=t+i
(n-n*jb-t)/(jb+1)<=i
n-(n+i)*jb>2*t+i-n
t+i 2*t
t 2*t+(i-n))
*/

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const int Maxp = 317000;

ll n, l, r, k;
ll res = -1;

void Solve1(ll lef, ll rig, ll k)
{
    for (ll i = lef; i <= rig && n + i <= k; i++)
        if (k % (n + i) == 0)
            res = max(res, ll(i));
}

void Solve2(ll lef, ll rig, ll k)
{
    for (ll z = 1; z * n <= k; z++)
        if (k % z == 0) {
            ll got = k / z - n;
            if (lef <= got && got <= rig)
                res = max(res, got);
        }
}

void Solve3(ll lef1, ll rig1, ll lef2, ll rig2, ll k)
{
    for (ll add = 0; add <= n; add++) {
        ll lftx = k % (n + add) - r;
        if (lftx < lef1) lftx += n + add;
        ll lfty = add - lftx;
        if (lef1 <= lftx && lftx <= rig1 &&
            lef2 <= lfty && lfty <= rig2)
            res = max(res, add);
    }
}

void Solve4(ll lef1, ll rig1, ll lef2, ll rig2, ll k)
{
    if (lef1 <= k && k <= rig1) res = max(res, k + rig2);
    for (ll z = 1; z * n <= k; z++) {
        ll myk = k - z * n - r;
        if (myk < 0) continue;
        ll all = myk / z;
        ll x = myk % z;
        ll y = all - x;
        if (x < lef1) {
            x += z;
            y -= (z + 1);
        }
        if (y > rig2) {
            ll tk = (y - rig2) / (z + 1);
            y -= tk * (z + 1);
            x += tk * z;
            if (y > rig2) {
                y -= (z + 1);
                x += z;
            }
        }
        if (lef1 <= x && x <= rig1 && lef2 <= y && y <= rig2)
            res = max(res, x + y);
    }
}

int main()
{
    cin >> n >> l >> r >> k;
    ll delt = l - 1;
    l = 1;
    r -= delt;
    if (r <= 0) r += n;
    if (r == n)
        if (n <= Maxp) {
            Solve1(0, n, k);
            Solve1(1, n, k + 1);
        } else {
            Solve2(0, n, k);
            Solve2(1, n, k + 1);
        }
    else if (n <= Maxp) {
        Solve3(0, r, 0, n - r, k);
        Solve3(1, r, 0, n - r, k + 1);
    } else {
        Solve4(0, r, 0, n - r, k);
        Solve4(1, r, 0, n - r, k + 1);
    }
    cout << res << endl;
    return 0;
}

#include <bits/stdc++.h>
#define pii pair<int,int>
#define pip pair<int,pii>
#define maxn 2020
#define debug
typedef long long ll;
using namespace std;

const int maxc = 1000000000;

int main(){

    ll n,k,l,r;
    scanf("%lld%lld%lld%lld",&n,&l,&r,&k);

    ll d = r-l+1;
    if(l > r){
        d = n-l+1+r;
    }

    if(d == n);// d = 0;
    if(n < 3e7){

        ll ans = -1;
        for(int i=0;i<=n;i++){

            ll res = k % (n+i);
            if(res < d) continue;
            if(res > 2*d) continue;
            ll u = res-d;
            if(u > i) continue;
            ll uu = i-u;
            if(n-d < uu-1) continue;
            ans = i;

        }
        printf("%lld\n",ans);
        return 0;
    }

    ll best = -1;
    for(int cyc=0;cyc<5000;cyc++){

            ll l = -1, r = 1e12;
            ll lo = 0, hi = n+1;
            while(lo != hi){
                ll mid = (lo+hi)/2;
                int ok = 1;
                if( k / (n + mid) > cyc) ok = 0;
                ll res = k - (ll) cyc * (n+mid);
                if(res > 2*d) ok = 0;
                if(res > d + mid) ok = 0;

                if(ok)
                    hi = mid;
                else
                    lo = mid+1;
            }
            l = lo;
             lo = -1, hi = n+1;
            while(lo != hi){
                ll mid = (lo+hi+1)/2;
                int ok = 1;
                if( k / (n + mid) < cyc) ok = 0;
                ll res = k - (ll) cyc * (n+mid);
                if(res < d) ok = 0;
                ll need = max(0ll,mid - (n-d)-1);
                if(cyc == 0 && mid == 5) debug("! %lld %lld\n",need,res);
                if(res < d + need) ok = 0;

                if(ok)
                    lo = mid;
                else
                    hi = mid-1;
            }
            r = lo;
            if(l == n+1 || k < (ll) cyc * n) r = -1;
            debug("cyc %d l %lld r %lld\n",cyc,l,r);
            if(l > r) continue;
            best = max(best,r);;

    }
    printf("%lld\n",best);
}

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll n, x, k, lb, ub, ans = -1;

void init() {
    ll l, r;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    x = (r >= l ? r - l + 1 : r + n - l + 1) % n;
}

void solve() {
    for(ll i = k, j, r; i; i = j) {
        j = k / (k / i + 1); r = k / i;
        ub = min(2 * n, i);
        lb = max(n, j + 1);
        ub = min(ub, min((2 * n + k - 2 * x + 1) / (r + 1), (k - x) / r));
        lb = max(lb, (k - 2 * x + r - 1) / r);
        if(ub >= lb) ans = max(ans, ub);
    }
    if(x <= k && k <= x * 2) ans = max(ans, n + min(k - x, x - 1) + n - x + 1);
    printf("%lld\n", ~ans ? ans - n : ans);
}

int main() {
    init();
    solve();
}

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll n, x, k, lb, ub, ans = -1;

void init() {
    ll l, r;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    x = (r >= l ? r - l + 1 : l + n - r + 1) % n;
}

void solve() {
    for(ll i = k, j, r; i; i = j) {
        j = k / (k / i + 1); r = k / i;
        ub = min(2 * n, i);
        lb = max(n, j + 1);
        ub = min(ub, min((2 * n + k - 2 * x) / (r + 1), (k - x) / r));
        lb = max(lb, (k - 2 * x) / r);
        if(ub >= lb) ans = max(ans, ub);
    }
    if(x <= k && k <= x * 2) ans = max(ans, n + max(k - x, x - 1) + n - x + 1);
    printf("%lld\n", ~ans ? ans - n : ans);
}

int main() {
    init();
    solve();
}

#include <bits/stdc++.h>

using namespace std;

#define X first
#define Y second

typedef long long ll;
typedef pair<ll, ll> pll;

const long long LIM = 1e6;

pll combine(pll a, pll b) {
    return pll(max(a.X, b.X), min(a.Y, b.Y));
}

long long solve(long long type, long long n, long long x, long long k) {
    k += type;
    if (n <= LIM) {
        long long ans = -1;
        for(long long i = type; i <= n; i++) {
            long long rem = k % (n + i);
            if (x + max(i - (n - x), type) <= rem && rem <= x + min(i, x)){
                ans = i;
            }
        }
        return ans;
    }
    long long ans = -1;
    ///no cycle
    if (x <= k && 2 * x >= k) return (k - x) + (n - x);
    for(long long cycle = 1; cycle * n <= k; cycle++){
        long long dL = (k - 1) / (cycle + 1) - n;
        long long dR = k / cycle - n;
        if (x <= n - x + type) {
            /// 1 -> x
            long long L1 = type, R1 = x;
            long long L2 = (k - cycle * n - x + cycle) / (cycle + 1);
            long long R2 = (k - cycle * n - x - type) / cycle;
            pll res = combine(pll(dL, dR), combine(pll(L1, R1), pll(L2, R2)));
            if (res.X <= res.Y) ans = max(ans, res.Y);

            L1 = x , R1 = (n - x + type);
            L2 = (k - cycle * n - 2 * x + cycle - 1) / cycle;
            R2 = (k - cycle * n - x - type) / cycle;
            res = combine(pll(dL, dR), combine(pll(L1, R1), pll(L2, R2)));
            if (res.X <= res.Y) ans = max(ans, res.Y);

            L1 = (n - x + type) , R1 = n;
            L2 = (k - cycle * n - 2 * x + cycle - 1) / cycle;
            R2 = (k - (cycle - 1) * n - 2 * x) / (cycle + 1);
            res = combine(pll(dL, dR), combine(pll(L1, R1), pll(L2, R2)));
            if (res.X <= res.Y) ans = max(ans, res.Y);
         }else {
            /// 1 -> n - x
            long long L1 = type, R1 = n - x + type;
            long long L2 = (k - cycle * n - x + cycle) / (cycle + 1);
            long long R2 = (k - cycle * n - x - type) / cycle;
            pll res = combine(pll(dL, dR), combine(pll(L1, R1), pll(L2, R2)));
            if (res.X <= res.Y) ans = max(ans, res.Y);

            L1 = n - x + type, R1 = x;
            L2 = (k - cycle * n - x + cycle) / (cycle + 1);
            R2 = (k - (cycle - 1) * n - 2 * x) / (cycle + 1);
            res = combine(pll(dL, dR), combine(pll(L1, R1), pll(L2, R2)));
            if (res.X <= res.Y) ans = max(ans, res.Y);

            L1 = x , R1 = n;
            L2 = (k - cycle * n - 2 * x + cycle - 1) / cycle;
            R2 = (k - (cycle - 1) * n - 2 * x) / (cycle + 1);
            res = combine(pll(dL, dR), combine(pll(L1, R1), pll(L2, R2)));
            if (res.X <= res.Y) ans = max(ans, res.Y);
        }
    }

    return ans;
}
int main() {
    long long n, tmpl, tmpr, k;
    cin >> n >> tmpl >> tmpr >> k;
    long long x = (tmpr - tmpl + n + 1) % n;
    cout << max(solve(0, n, x, k), solve(1, n, x, k));
}

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <cassert>
#include <string.h>
#include <unordered_set>
#include <unordered_map>

using namespace std;

typedef long long int64;
typedef unsigned long long uint64;
#define two(X) (1<<(X))
#define twoL(X) (((int64)(1))<<(X))
#define contain(S,X) (((S)&two(X))!=0)
#define containL(S,X) (((S)&twoL(X))!=0)
const double pi=acos(-1.0);
const double eps=1e-11;
template<class T> inline void ckmin(T &a,T b){if(b<a) a=b;}
template<class T> inline void ckmax(T &a,T b){if(b>a) a=b;}
template<class T> inline T sqr(T x){return x*x;}
typedef pair<int,int> ipair;
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()

int64 solve1(int64 n,int64 c,int64 d)
{
	if (c==1) return (d==0)?n:-1;
	int64 ret=-1;
	for (int bit=1;bit<=2;bit++) if (bit<=c)
		for (int64 m=n;m<=n+n;m++)
		{
			int64 z=(c-bit)%m;
			if (z<d || z>d+d) continue;
			if (z+bit+(n-d-1)>m || z+bit+(n-d-1)*2<m) continue;
			ckmax(ret,m-n);
		}
	return ret;
}
int64 solve2(int64 n,int64 c,int64 d)
{
	if (c==1) return (d==0)?n:-1;
	int64 ret=-1;
	for (int bit=1;bit<=2;bit++) if (bit<=c)
	{
		if (c-bit>=d && c-bit<=d+d)
			ckmax(ret,c+(n-d-1)*2-n);
		for (int64 cnt=1;cnt<=(c-bit)/n;cnt++)
		{
			int64 t=(c-bit)/cnt;
			int64 s=(c-bit)/(cnt+1)+1;
			ckmax(s,n);
			ckmin(t,n+n);
			if (s>t) continue;
			ckmin(t,(c-bit-d)/cnt);
			ckmax(s,(c-bit-d-d+cnt-1)/cnt);
			if (s>t) continue;
			ckmin(t,(c+2*(n-d-1))/(cnt+1));
			ckmax(s,(c+(n-d-1)+cnt)/(cnt+1));
			if (s>t) continue;
			ckmax(ret,t-n);
		}
	}
	return ret;
}

int main()
{
#ifdef _MSC_VER
	freopen("input.txt","r",stdin);
#endif
	std::ios::sync_with_stdio(false);
	int64 n,k,l,r;
	while (cin>>n>>l>>r>>k)
	{
		int64 d=(r-l+n)%n;
		int64 ret;
		if (n<=1000000)
			ret=solve1(n,k,d);
		else
			ret=solve2(n,k,d);
		cout<<ret<<endl;
#ifndef _MSC_VER
		break;
#endif
	}
	return 0;
}

/* cerberus97 - Hanit Banga */

#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>

using namespace std;

#define pb push_back
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;

const int N = 1e5 + 10, SWITCH = 4600;

// return a % b (positive value)
ll mod(ll a, ll b) {
  return ((a%b)+b)%b;
}

// computes gcd(a,b)
ll gcd(ll a, ll b) {
  ll tmp;
  while(b){a%=b; tmp=a; a=b; b=tmp;}
  return a;
}

// computes lcm(a,b)
ll lcm(ll a, ll b) {
  return a/gcd(a,b)*b;
}

// returns d = gcd(a,b); finds x,y such that d = ax + by
ll extended_euclid(ll a, ll b, ll &x, ll &y) {
  ll xx = y = 0;
  ll yy = x = 1;
  while (b) {
    ll q = a/b;
    ll t = b; b = a%b; a = t;
    t = xx; xx = x-q*xx; x = t;
    t = yy; yy = y-q*yy; y = t;
  }
  return a;
}

// computes b such that ab = 1 (mod n), returns -1 on failure
ll mod_inverse(ll a, ll n) {
  ll x, y;
  ll d = extended_euclid(a, n, x, y);
  if (d > 1) return -1;
  return mod(x,n);
}

void solve1(ll n, ll l, ll r, ll k);
void solve2(ll n, ll l, ll r, ll k) ;
ll maximize(ll a, ll b, ll c, ll d1, ll d2);

int main() {
	fast_cin();
	ll n, l, r, k;
	cin >> n >> l >> r >> k;
	int dist = l - 1;
	l -= dist;
	r -= dist;
	if (r < 1) {
		r += n;
	}
	if (n <= SWITCH) {
		solve1(n, l, r, k);
	} else {
		solve2(n, l, r, k);
	}
}

void solve1(ll n, ll l, ll r, ll k) {
	int best = -1;
	for (int s1 = 0; s1 <= r; ++s1) {
		for (int s2 = 0; s2 <= n - r; ++s2) {
			ll num = k - r - s1;
			ll den = s1 + s2 + n;
			if (num % den == 0) {
				ll a = num / den;
				if (a >= 0 and a * n <= k) {
					best = max(best, s1 + s2);
				}
			}
			if (s1 == 0) {
				continue;
			}
			++num;
			if (num % den == 0) {
				ll a = num / den;
				if (a >= 0 and a * n <= k) {
					best = max(best, s1 + s2);
				}
			}
		}
	}
	cout << best << endl;
}

void solve2(ll n, ll l, ll r, ll k) {
	ll a_mx = k / n, best = -1;
	for (ll a = 0; a <= a_mx; ++a) {
		if (k - r - a * n < 0) {
			break;
		}
		best = max(best, maximize(a + 1, a, k - r - a * n, r, n - r));
		best = max(best, maximize(a + 1, a, k - r - a * n - a, r - 1, n - r) + 1);
	}
	cout << best << endl;
}

ll maximize(ll a, ll b, ll c, ll d1, ll d2) {
	if (b < a) {
		swap(a, b);
		swap(d1, d2);
	}
	ll num = c - b * d2;
	ll den = a;
	num = (num + den - 1) / den;
	ll lo = max(0ll, num);
	ll hi = d1;
	ll g = __gcd(a, b);
	if (c % g) {
		return -5;
	}

	ll inv = mod_inverse(a, b / g);
	if (inv == -1) {
		return -5;
	}
	inv = (inv * c) % (b / g);
	ll i = ((hi - inv) * g) / b;
	ll x1 = i * (b / g) + inv;
	if (lo <= x1 and x1 <= hi) {
		ll x2 = (x1 * (b - a) + c) / b;
		return x1 + x2;
	}
}

#include <bits/stdc++.h>
#define mp make_pair
#define X first
#define Y second
#define pii pair<ll,ll>
#define x1 dlfjl
#define x2 dkfj
#define x3 dflgkg
#define y1 dskgj
#define y2 dskfj
#define y3 dfhgdh
#define SQ 320
#define PI 3.14159265359
#define MOD 1000000007
#define MAXN 1000005
typedef long long ll;
using namespace std;
ll i,j,k,z,q,timer,x,y,n,m, cnt, even, flag, x1,y1,x2,y2, boom,r,c;
vector<pii> f, f1;
ll solve(ll n, ll l, ll r, ll k, ll id) {
    ll C1 = 2*(r-l+1)-k;
    ll C2 = k - (r-l+1);
    ll m1 = -C1/(2*n) - 5;
    ll m2 = C2/n - 5;
    //cout << C1 << " " << C2 << endl;
    while (2*m1*n + C1 < 0)
        m1++;
    while (C2 - m2*n - n >= 0)
        m2++;
    //cout << m1 << " " << m2 << endl;
    if (m1 > m2) {
        return -1;
    }

    ll ans = -1;
    if (m1 == 0) {
        ll diff = k-(r-l+1);
        if (diff >= id && diff <= r-l+1)
            ans = diff + n-(r-l+1);
        m1++;
    }
    //cout << m1 << " " << m2 << endl;
    for (ll i = m1; i <= min(m2, m1+400000); i++) {
        ll T = k - (r-l+1);
        ll x, y;
        ll K = 0;
        ll puk = 40;
        for (int j  = 0; j < 40; j++)
        if (i*(1LL<<j) > (ll)1e+15) {
            puk = j;
            break;
        }
        //cout << puk << endl;
        //cout << T/i << " " << T%i << endl;
        for (int j = puk; j >= 0; j--) {
            K += (1LL<<j);
            if (T/i - K - T % i - i * K - n <= n-(r-l+1))
                K -= (1LL<<j);
        }
        if (!(T/i - K - T % i - i * K - n <= n-(r-l+1)))
            K++;
        y = T/i-K-T%i-i*K - n;
        x = (T - y*i - n*i)/(i+1);
        //cout << T << " " << x << " " << y << endl;
        if (x >= id && x <= r-l+1 && y >= 0 && y <= n-(r-l+1))
            ans = max(ans, x+y);
    }

    for (ll i = max(m1, m2-400000); i <= m2; i++) {
        ll T = k - (r-l+1);
        ll x, y;
        ll K = 0;
        ll puk = 40;
        for (int j  = 0; j < 40; j++)
        if (i*(1LL<<j) > (ll)1e+15) {
            puk = j;
            break;
        }
        //cout << puk << endl;
        //cout << T/i << " " << T%i << endl;
        for (int j = puk; j >= 0; j--) {
            K += (1LL<<j);
            if (T/i - K - T % i - i * K - n <= n-(r-l+1))
                K -= (1LL<<j);
        }
        if (!(T/i - K - T % i - i * K - n <= n-(r-l+1)))
            K++;
        y = T/i-K-T%i-i*K - n;
        x = (T - y*i - n*i)/(i+1);
        //cout << T << " " << x << " " << y << endl;
        if (x >= id && x <= r-l+1 && y >= 0 && y <= n-(r-l+1))
            ans = max(ans, x+y);
    }

    return ans;
}
int main() {
    //freopen("input.txt", "r", stdin);
    ll n, l, r, k;
    cin >> n >> l >> r >> k;
    if (l > r) {
        r += n;
    }
    ll ans1 = solve(n,l,r,k,0);
    ll ans2 = solve(n,l,r,k+1,1);
    //cout << ans1 << " " << ans2 << endl;
    cout << max(ans1, ans2) << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
	ll	n, k, l, r;
	scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
	r = (r - l + 1 + n) % n;
	if(n <= k / n)
	{
		for(ll i = n; ~i; i--)
		{
			ll	res = k % (n + i) - r;
			if(res >= 0 && res <= r && res <= i)
				return printf("%lld\n", i), 0;
		}
		puts("-1");
	}
	else
	{
		ll	ans = -1;
		if(k >= r && k <= r * 2)
			ans = max(ans, min(k - r + 1, r) + n - r);
		for(ll i = 1; i <= k / n; i++)
		{
			ll	r0 = min((k - 2 * r + 2 * n) / (i + 1), (k - r) / i);
			ll	l0 = max((k - 2 * r + i - 1) / i, (k - r + n) / (i + 1) + 1);
			if(l0 <= r0)
				ans = max(ans, r0 - n);
		}
		printf("%lld\n", ans);
	}
	return 0;
}

#include <bits/stdc++.h>
// #pragma GCC optimize ("O3")
// #pragma GCC target ("sse4")
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;

#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for (int i=(a); i<(b); ++i)
#define FORD(i,a,b) for (int i=(a)-1; i>=(b); --i)

#define pb push_back
#define mp make_pair
#define st first
#define nd second

const int MOD = 1000000007;

LL check(LL N, LL K, LL incomplete, LL o) {
  if (o == 0) {
    if (K < incomplete) return -1;
    if (K > 2*incomplete) return -1;
    return K - incomplete + (K < 2*incomplete) + (N - incomplete);
  }

  if (K / o < N) return -1;

  K -= o*N + incomplete;
  if (K < 0) return -1;

  LL S = K % o;
  if (S > incomplete) return -1;
  if (K / (o+1) < S) return -1;
  K -= (o+1) * S;
  incomplete -= S;
  N -= S;

  if (K == 0) return S;
  if (N == 0) return -1;

  LL res = -1;
  // 1. ostatni wziął
  {
    LL max_in_other = o * (N - incomplete);
    LL min_in_incomplete = (K - max_in_other + o) / (o+1);
    if (min_in_incomplete % o) {
      min_in_incomplete = (min_in_incomplete - min_in_incomplete % o) + o;
    }
    bool ok = true;
    if (min_in_incomplete > incomplete) ok = false;
    LL in_other = (K - min_in_incomplete * (o+1)) / o;
    if (in_other > N - incomplete) ok = false;
    if (ok) res = max(res, in_other + min_in_incomplete + S);
  }

  // 2. ostatni nie wziął
  {
    if (incomplete == 0) return res;
    --incomplete;

    LL max_in_other = o * (N - incomplete);
    LL min_in_incomplete = (K - max_in_other + o) / (o+1);
    if (min_in_incomplete % o) {
      min_in_incomplete = (min_in_incomplete - min_in_incomplete % o) + o;
    }
    bool ok = true;
    if (min_in_incomplete > incomplete) ok = false;
    LL in_other = (K - min_in_incomplete * (o+1)) / o;
    if (in_other > N - incomplete) ok = false;
    if (ok) res = max(res, in_other + min_in_incomplete + S);
  }

  return res;
}

LL N, L, R, K, incomplete;

int main() {
  ios_base::sync_with_stdio(0);

  cin >> N >> L >> R >> K;

  incomplete = (R-L+1 + N) % N;
  if (!incomplete) incomplete = N;

  LL result = -1;
  REP(o,1e6) result = max(result, check(N, K, incomplete, o));
  REP(r,min(N+1,(LL)1e6)) {
    LL o = K / (N + r);
    result = max(result, check(N, K, incomplete, o));
  }
  cout << result << endl;
}

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <cmath>
#define all(x) (x).begin(),(x).end()
#define size(x) ((int)(x).size())
#define FIRST first
#define SECOND second
#define FRONT front
#define PUSH_BACK push_back
#define MAKE_PAIR make_pair
#define EMPTY empty
#define PRIORITY_QUEUE priority_queue
using namespace std;
typedef long long LL;
typedef unsigned int uii;
typedef pair<int,int> pii;
typedef unsigned long long uLL;
typedef vector<int> vii;
// const double PI = acos(-1.0);
//head
const LL inf = 1e12;
const LL num = 2e6;
LL n, l, r, k;

void exgcd(LL a, LL b, LL &x, LL &y, LL &d){
	if(b){
		exgcd(b, a % b, y, x, d);
		y -= a / b * x;
	} else {
		d = a;
		x = 1, y = 0;
	}
}

int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
	// freopen("out.txt", "w", stdout);
#endif
	// ios::sync_with_stdio(false);
	// cin.tie(0);
	// 初始化 图的连通性 排序
	cin >> n >> l >> r >> k;
	LL b = (r - l + 1 + n) % n;
	LL a = n - b;
	if(k <= 2 * b){
		if(k < b){
			cout << -1 << endl;
		} else if(k < 2 * b){
			cout << a + k - b + 1 << endl;
		} else {
			cout << n << endl;
		}
		return 0;
	}
	if(n <= num){
		LL res = -1;
		if(k < n + b) {
			cout << -1 << endl;
			return 0;
		}
		for(int i = 2 * n; i >= n; --i){
			LL x = k % i;
			LL y = i - x;
			if(b <= x && x <= 2 * b && a <= y && y <= 2 * a){
				res = max(res, x - b + y - a);
			}
		}
		cout << res << endl;
		return 0;
	} else {
		// LL res = -1;
		/*LL st = k / (2 * n), ed = k / n;
		for(int d = st; d <= ed; ++d){
			LL i = (a + k + d) / (d + 1);
			LL x = -k + i * (d + 1);
			LL y = k - i * d;
			if()
		}*/
		LL i = min(2 * a, 2 * b);
		if(i < a || i < b) cout << - 1 << endl;
		else cout << i - n << endl;
		return 0;
	}
	cout << -1 << endl;
	return 0;
}

#include <cstdio>

typedef long long ll;

const ll X = 2e5;

int main() {
    ll n, l, r, k;
    scanf("%lld %lld %lld %lld", &n, &l, &r, &k);
    r = (r - l + 1 + n) % n;

    ll ans = -1;
    if (n <= X) {
        for (ll i = n; i >= 0; i--) {
            ll y = k % (n + i) - r;
            if (y < 0 || y > r || y > i || y < i + r - n - 1) {
                continue;
            }
            ll y2 = y + 1;
            if (y2 <= r && y2 <= i) {
                ans = i;
                break;
            }
            if (y >= i + r - n) {
                ans = i;
                break;
            }
        }
    } else {
        for (ll i = 0; i <= k / n; i++) {
            ll p = (k - (i - 1) * n - 2 * r + 1) / (i + 1);
            ll y = k - i * (n + p) - r;
            if (y < 0) {
                if (i == 0) {
                    continue;
                }
                int d = (-y - 1) / i + 1;
                y += i * d;
                p -= d;
            }
            if (p > n) {
                y += i * (p - n);
                p = n;
            }
            if (y < 0 || y > r || y > p || p < 0 || y + 1 < p + r - n) {
                continue;
            }
            ll y2 = y + 1;
            if (y >= p + r - n) {
                if (p > ans) {
                    ans = p;
                }
            }
            if (y2 <= r && y2 <= p) {
                if (p > ans) {
                    ans = p;
                }
            }
        }
    }

    printf("%lld\n", ans);

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll n, l, r, k;
int main(){
	scanf("%lld %lld %lld %lld", &n, &l, &r, &k);
	r=(r-l+n)%n+1;
	if(n<=5e5){
		//O(n)
		for(ll i=n; i>=0; i--){
			ll dv=n+i;
			ll m=(dv+k-r-min(i, r)-1)/dv-1;
			ll M=(dv+k-r-max(r-(n-i+1), 0ll))/dv-1;
			if(M>m){
				printf("%lld\n", i);
				return 0;
			}
		}
	}else{
		//O(k/n)
		for(ll i=0; i<=(n+k-r)/n-1; i++){
			ll dv=i+1;
			ll s1=k-i*n-r-1;
			ll s2=s1-r+n+1;
			ll m=(dv+s1)/dv-1;
			ll M=min(n, (dv+s2)/dv-1);
			if(i>0) m=max(m, (i+s2)/i-1);
			if(i>0) M=min(M, (s1)/i);
			if(M>m){
				printf("%lld\n", M);
				return 0;
			}
		}
	}
	printf("-1\n");
	return 0;
}

#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <cmath>
#include <unordered_map>
#include <queue>
#include <map>
#include <functional>
#include <stack>
#include <cmath>
#include <cstring>
#include <random>
#include <chrono>
#include <memory>
#include <cassert>
#include <numeric>
#include <array>
#define int long long
#define pii pair<int, int>
#define pic pair<int, char>
#define pdd pair<double, double>
#define x first
#define y second
#define ll long long
#define ull unsigned long long
#define endl "\n"
#define all(a) (a).begin(), (a).end()
#pragma GCC optimize ("O3")

using namespace std;

const int N = 2e3 + 10;
const int inf = 1e18 + 10ll;
const int mod = 1e9 + 7;
const int eps = 1e-9;

mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());

using namespace std;

int n, l, r, k;
int len1;
int len2;

int gcd(int a, int b, int &x, int &y) // a >= b
{
	if (b == 0)
	{
		x = 1;
		y = 0;
		return a;
	}

	int g = gcd(b, a % b, x, y);
	int nx = y;
	int ny = x - y * (a / b);
	x = nx;
	y = ny;
	return g;
}

bool findsol(int a, int b, int c, int &x0, int &y0)
{
	int g = gcd(a, b, x0, y0);

	if (c % g != 0)
		return false;

	x0 *= c / g;
	y0 *= c / g;
	return true;
}

void shift(int &x, int &y, int a, int b, int cnt)
{
	x += b * cnt;
	y -= a * cnt;
}

bool findmxsol(int a, int b, int c, int &x, int &y)
{
	int x0, y0;

	if (!findsol(a, b, c, x0, y0))
		return false;

	int tmp1, tmp2, g = gcd(a, b, tmp1, tmp2);

	a /= g; b /= g;

	if (x < len1)
		shift(x, y, a, b, (len1 - x) / b);

	if (x > len1)
		shift(x, y, a, b, -((x - len1 + b - 1) / b));

	pii p1 = { a, b };

	if (x < 1 || x > len1 || y < 1 || y > len2)
		p1 = { -1, -1 };

	if(x < 1)
		shift(x, y, a, b, (1 - x + b - 1) / b);

	if(x > 1)
		shift(x, y, a, b, -(x - 1) / b);

	pii p2 = { a, b };

	if (x < 1 || x > len1 || y < 1 || y > len2)
		p2 = { -1, -1 };

	if (y < len2)
		shift(x, y, a, b, -(len2 - y) / a);

	if (y > len2)
		shift(x, y, a, b, (y - len2 + a - 1) / a);

	pii p3 = { a, b };

	if (x < 1 || x > len1 || y < 1 || y > len2)
		p3 = { -1, -1 };

	if (y < 1)
		shift(x, y, a, b, -(1 - y + a - 1) / a);

	if (y > 1)
		shift(x, y, a, b, (y - 1) / a);

	pii p4 = { a, b };

	if (x < 1 || x > len1 || y < 1 || y > len2)
		p4 = { -1, -1 };

	pii mxp = { -1, -1 };

	if (p1.x <= len1 && p1.y <= len2 && p1.x >= 1 && p1.y >= 1 && (mxp.x + mxp.y < p1.x + p1.y))
		mxp = p1;

	if (p2.x <= len1 && p2.y <= len2 && p2.x >= 1 && p2.y >= 1 && (mxp.x + mxp.y < p2.x + p2.y))
		mxp = p2;

	if (p3.x <= len1 && p3.y <= len2 && p3.x >= 1 && p3.y >= 1 && (mxp.x + mxp.y < p3.x + p3.y))
		mxp = p3;

	if (p4.x <= len1 && p4.y <= len2 && p4.x >= 1 && p4.y >= 1 && (mxp.x + mxp.y < p4.x + p4.y))
		mxp = p4;

	x = mxp.x;
	y = mxp.y;

	return true;
}

pii calc(int t, bool is)
{
	int y = k - n * t - len1 + is;
	pii p = { -1, -1 };

	findmxsol((t + 1), t, y, p.x, p.y);

	return p;
}

int mul(int a, int b)
{
	if (a <= 1e9 && b <= 1e9)
		return a * b;

	return inf;
}

int32_t main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	cout.precision(10);

	cin >> n >> l >> r >> k;

	if (r < l)
		len1 = (n - l) + r + 1;
	else
		len1 = r - l + 1;

	len2 = n - len1;

	int ans = -1;

	if (mul(len1 + 1, len2 + 1) <= 1e8)
	{
		for (int i = 0; i <= len1; ++i)
			for (int j = 0; j <= len2; ++j)
			{
				int cur = k - i * 2 - (len1 - i);
				int sum = (i + j) * 2 + (n - i - j);

				if (!cur || (sum && (cur % sum == 0 || (i && (cur + 1) % sum == 0))))
					ans = max(ans, i + j);
			}
	}
	else
	{
		int kneed = (k + 1) / 2;

		if (kneed <= len1 && kneed + k / 2 >= len1)
			ans = max(ans, k / 2 - (len1 - kneed) + len2);

		++k;
		kneed = (k + 1) / 2;

		if (kneed <= len1 && kneed + k / 2 >= len1)
			ans = max(ans, k / 2 - (len1 - kneed) + len2);

		--k;

		for (int i = 1; i <= k / n; ++i)
		{
			int y1 = k - n * i - len1;
			int y2 = k - n * i - len1 + 1;
			pii p1 = calc(i, false);
			pii p2 = calc(i, true);

			if (p1.x <= len1 && p1.y <= len2 && ((i + 1) * p1.x + i * p1.y == y1) && y1 >= 0 && p1.x >= 0 && p1.y >= 0)
				ans = max(ans, p1.x + p1.y);

			if (p2.x <= len1 && p2.y <= len2 && ((i + 1) * p2.x + i * p2.y == y2) && y2 >= 0 && p2.x >= 1 && p2.y >= 0)
				ans = max(ans, p2.x + p2.y);
		}
	}

	cout << ans << endl;
}

/*

y = k - n * t

(t + 1) * a + t * b = y

b = y / t
a = (y - t * b) / (t + 1)
*/

/* cerberus97 - Hanit Banga */

#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>

using namespace std;

#define pb push_back
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;

const int N = 1e5 + 10;
const ll inf = 1e18;

void solve1(ll n, ll r, ll k);
void solve2(ll n, ll r, ll k) ;
ll maximize(ll a, ll c, ll d1, ll d2);

int main() {
	fast_cin();
	ll n, l, r, k;
	cin >> n >> l >> r >> k;
	r -= l - 1;
	if (r < 1) {
		r += n;
	}
	if (ld(n) * n <= k / n) {
		solve1(n, r, k);
	} else {
		solve2(n, r, k);
	}
}

void solve1(ll n, ll r, ll k) {
	ll best = -1;
	for (ll s1 = 0; s1 <= r; ++s1) {
		for (ll s2 = 0; s2 <= n - r; ++s2) {
			ll num = k - r - s1;
			ll den = s1 + s2 + n;
			if (num % den == 0) {
				ll a = num / den;
				if (a >= 0 and a * n <= k) {
					best = max(best, s1 + s2);
				}
			}
			if (s1 == 0) {
				continue;
			}
			++num;
			if (num % den == 0) {
				ll a = num / den;
				if (a >= 0 and a * n <= k) {
					best = max(best, s1 + s2);
				}
			}
		}
	}
	cout << best << endl;
}

void solve2(ll n, ll r, ll k) {
	ll a_mx = k / n, best = -1;
	for (ll a = 0; a <= a_mx; ++a) {
		best = max(best, maximize(a, k - r - a * n, n - r, r));
		best = max(best, 1 + maximize(a, k - r - a * n - a, n - r, r - 1));
	}
	cout << best << endl;
}

// Maximize x + y when ax + (a + 1)y = c, subject to 0 <= x <= d1 and 0 <= y <= d2
ll maximize(ll a, ll c, ll d1, ll d2) {
	if (a == 0) {
		return ((0 <= c and c <= d2) ? d1 + c : -inf);
	}
	ll x = ((-c % (a + 1)) + (a + 1)) % (a + 1);
	ll i = (d1 - x) / (a + 1);
	x += i * (a + 1);
	if (0 <= x and x <= d1) {
		ll y = (c - a * x) / (a + 1);
		if (0 <= y and y <= d2) {
			return x + y;
		}
	}
	return -inf;
}

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <tuple>
#include <iterator>
#include <cmath>

using namespace std;

const long long THR = 5000;

int main()
{
    //freopen("in", "r", stdin);
    //freopen("out", "w", stdout);

    long long n, l, r, k;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);

    long long d = r - l + 1;
    while(d <= 0)
        d += n;

    if(k < d)
    {
        puts("-1");
        return 0;
    }

    long long res = -1;
    if(n < THR)
    {
        for(long long i = 0; i <= d; i++)
        {
            for(long long j = 0; j <= (n - d); j++)
            {
                long long t = k - (d + i);
                if(t == 0 || i > 0 && t == -1)
                {
                    res = max(res, i + j);
                    continue;
                }

                long long q = t / (n + i + j);
                long long t2 = t - q * (n + i + j);
                if(q >= 0 && (t2 == 0 || i > 0 && t2 == -1))
                {
                    res = max(res, i + j);
                    continue;
                }

                long long t3 = t - (q + 1) * (n + i + j);
                if(q + 1 >= 0 && (t3 == 0 || i > 0 && t3 == -1))
                {
                    res = max(res, i + j);
                    continue;
                }
            }
        }
    }
    else
    {
        long long s, g;
        s = max(0LL, (k / 2 - d) / n - 10);
        g = max(s, (k - d) / n + 10);

        for(long long i = s; i <= g; i++)
        {
            if(k < d + n * i)
                continue;

            if(k > 2 * (d + n * i) + 1)
                continue;

            if(i == 0)
            {
                res = max(res, min(d, k + 1 - d) + n - d);
                continue;
            }

            {
                long long t = k - (d + n * i);

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(q >= 0 && r1 == 0)
                            res = max(res, n - d + min(d, q));
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(q >= 0 && r1 == 0)
                            res = max(res, min(n - d, q));
                    }
                }
            }

            {
                long long t = k + 1 - (d + n * i);
                t -= i + 1;

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(q >= 0 && r1 == 0)
                            res = max(res, n - d + min(d, q + 1));
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(q >= 0 && r1 == 0)
                            res = max(res, min(n - d, q + 1));
                    }
                }
            }
        }
    }

    printf("%lld\n", res);
    return 0;
}

//��CF1063D
#include<iostream>
#include<cstdio>
#include<fstream>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<bitset>
#include<cmath>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef long long LL;
typedef double DB;
LL n,k,e,x,y,z,w,s=-1;
void solve1(){
	LL i;
	for(i=0;i<=n;i=i+1){
		x=k%(n+i);
		if(x<e||e+e<x)
			continue;
		y=x-e;
		if(y>i||(e-y)>(n-i))
			continue;
		s=max(s,i);
	}
	k++;
	for(i=1;i<=n;i=i+1){
		x=k%(n+i);
		if(x<e||e+e<x)
			continue;
		y=x-e;
		if(!y||y>i||(e-y)>(n-i))
			continue;
		s=max(s,i);
	}
}
void solve2(){
	LL i;
	if(e<=k&&k<=e+e)
		s=max(s,k-e+n-e);
	for(i=1;n*i+e<=k;i=i+1){
		x=k-n*i-e;
		if(x>n*i+e)
			continue;
		y=x%i;
		if(y>e)
			continue;
		x-=y*(i+1);
		z=min(n-e,x/i);
		x-=z*i;
		if(x){
			x/=i;
			w=x/(i+1);
			y+=w*i;
			x-=w*(i+1);
			if(x){
				w=(LL)i+1-x;
				z-=w;
				y+=i;
			}
		}
		if(y>e||y<0||z>n-e||z<0)
			continue;
		s=max(s,y+z);
	}
	k++;
	if(e+1<=k&&k<=e+e)
		s=max(s,k-e+n-e);
	for(i=1;n*i+e<=k;i=i+1){
		x=k-n*i-e;
		if(x>n*i+e)
			continue;
		y=x%i;
		if(y>e)
			continue;
		x-=y*(i+1);
		z=min(n-e,x/i);
		x-=z*i;
		if(x){
			x/=i;
			w=x/(i+1);
			y+=w*i;
			x-=w*(i+1);
			if(x){
				w=(LL)i+1-x;
				z-=w;
				y+=i;
			}
		}
		if(y>e||y<0||z>n-e||z<0)
			continue;
		if(!y)
			y=i,z-=i+1;
		if(y>e||y<0||z>n-e||z<0)
			continue;
		s=max(s,y+z);
	}
}
int main()
{
	cin>>n>>x>>y>>k;
	e=(y-x+n)%n+1;
	if(n<=1e6)
		solve1();
	else
		solve2();
	cout<<s;
	return 0;
}

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <tuple>
#include <iterator>
#include <cmath>

using namespace std;

const int THR = 5000;

int main()
{
    //freopen("in", "r", stdin);
    //freopen("out", "w", stdout);

    long long n, l, r, k;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);

    long long d = (r - l + 1) % n;
    while(d <= 0)
        d += n;

    if(k < d)
    {
        puts("-1");
        return 0;
    }

    long long res = -1;
    if(n < THR)
    {
        for(long long i = 0; i <= d; i++)
        {
            for(long long j = 0; j <= (n - d); j++)
            {
                long long t = k - (d + i);
                if(t == 0 || i > 0 && t == -1)
                {
                    res = max(res, i + j);
                    continue;
                }

                long long q = t / (n + i + j);
                long long t2 = t - q * (n + i + j);
                if(t2 == 0 || i > 0 && t2 == -1)
                {
                    res = max(res, i + j);
                    continue;
                }

                long long t3 = t - (q + 1) * (n + i + j);
                if(t3 == 0 || i > 0 && t3 == -1)
                {
                    res = max(res, i + j);
                    continue;
                }
            }
        }
    }
    else
    {
        long long s, g;
        s = max(0LL, (k / 2 - d) / n);
        g = max(s, (k - d) / n);

        for(long long i = s; i <= g; i++)
        {
            if(k < d + n * i)
                break;

            if(k > 2 * (d + n * i))
                continue;

            if(i == 0)
            {
                res = max(res, min(d, k + 1 - d) + n - d);
                continue;
            }

            {
                long long t = k - (d + n * i);

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(r1 == 0)
                            res = max(res, n - d + q);
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(r1 == 0)
                            res = max(res, q);
                    }
                }
            }
            {
                long long t = k + 1 - (d + n * i);
                t -= i + 1;

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(r1 == 0)
                            res = max(res, n - d + q + 1);
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(r1 == 0)
                            res = max(res, q + 1);
                    }
                }
            }
        }
    }

    printf("%lld\n", res);
    return 0;
}

#include<bits/stdc++.h>
using namespace std;

#define ull unsigned long long
#define ll long long
#define ud unsigned int
#define ind(x) scanf("%d",&x)
#define inlld(x) scanf("%I64d",&x)
#define inud(x) scanf("%u",&x)
#define inulld(x) scanf("%ull",&x)
#define inc(x) scanf("%c",&x)
#define incf(x) scanf("%f",&x)
#define inlf(x) scanf("%lf",&x)
#define inLf(x) scanf("%Lf",&x)

#define LL(x) ((x)<<1)
#define RR(x) (((x)<<1)|1)
#define FF(i,s,n) for(int i = s; i < n ; ++i)
#define println() printf("\n")

ll n, l, r, k, c;
int extgcd(ll a, ll b, ll &x, ll &y)
{
    if (b == 0)
    {
        x = 1;
        y = 0;
        return a;
    }
    int gcd = extgcd(b, a%b, y, x);
    y -= a / b * x;
    return gcd;
}
int main()
{
#ifdef _DEBUG
    freopen("D:\\temp\\input.txt", "r", stdin);
#define gets gets_s
#endif
    ll p = -1;
    inlld(n); inlld(l); inlld(r); inlld(k);
    if ((k / n) / n > n||n<2e4)
    {
        ll x, y;
        if (r < l)
            x = n - l + r + 1, y = n - x;
        else
        {
            x = r - l + 1, y = n - x;
        }
        if (k - x <= x && k - x >= 0)p = min(n, k - x + y + 1);;
        for (ll a = 0; a <= min(x, k - x); a++)
            for (ll b = 0; b <= y; b++)
                if ((k - x - a) % (n + a + b) == 0 || (k + 1 - x - a) % (n + a + b) == 0)p = max(p, a + b);
    }
    else
    {
        ll x, y;
        if (r < l)
            x = n+ r - l + 1, y = n - x;
        else
        {
            x = r - l + 1, y = n - x;
        }
        if (k - x <= x && k - x >= 0)p = min(n, k - x + y + 1);
        ll up = min(k / n + 1, (k - x) / x + y);
        for (int t = 1; t <= up; t++)
        {
            ll z = k - (t + 1)*x - y * t;
            if (z <= 0)break;
            ll x0, y0, X, Y, xx, yy;
            ll beta;
            int gcd = extgcd(t + 1, t, x0, y0);
            X = x0, Y = y0;
            x0 *= z;
            y0 *= z;
            xx = floor(1.0*x0 / t);
            yy = floor(1.0*(y - y0) / (t + 1));
            if ((x0 - x) / t > (y - y0) / (t + 1) || xx < -y0 / (t + 1))continue;
            if (xx <= yy)
                beta = xx;
            else beta =yy;
            x0 = x0 - t * beta;
            y0 = y0 + (t + 1)*beta;
            if (x0 +y0 > n)continue;
            if (x0 > x || y0  > y)continue;
            p = max(p, x0 + y0);
            //if ((xx + 1)*(t + 1) - 1 + yy * t == z) p = max(p, xx + yy + 1);
            //gcd = extgcd(t + 1, t, x0, y0);
            x0 = X, y0 = Y;
            if (z >= 1)
            {
                x0 *= z + 1;
                y0 *= z + 1;
                xx = floor(1.0*x0 / t);
                yy = floor(1.0*(y - y0) / (t + 1));
                if ((x0 - x) / t > (y - y0) / (t + 1) || xx < -y0 / (t + 1))continue;
                if (xx <= yy)
                    beta = xx;
                else beta = yy;
                x0 = x0 - t * beta;
                y0 = y0 + (t + 1)*beta;
                if (x0 + y0 > n)continue;
                if (x0 > x || y0 > y)continue;
                p = max(p, x0 + y0);
            }
        }
    }
    printf("%I64d\n", p);
}

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,l,r,k,d,ans=-1;
main(){
	cin>>n>>l>>r>>k,d=(r-l+n)%n+1;
	if(n<=3e6)for(int i=n;i>=0;i--){
	 int res=k%(i+n)-d;
	 if(res>=0&&res<=d&&res<=i){ans=i;break;}
	}else
	for(int c=k/n,i=0;i<=c;i++){
		int res=(k-2*d-n*(i-1))/(i+1);
		int z=k-i*(res+n)-d,a;
		if(z<0){
			a=ceil((-z)*1.0/i);
			if(a*i+z<=res-a&&a*i+z<=d)ans=max(ans,res-a);
		}else if(z<=d&&z<=res&&res<=n)ans=max(ans,res);
		else if(res>=n){
			if((res-n)*i+z<=d)ans=max(ans,res);
		}
		else {
			a=min(d,res),a=ceil((z-a)*1.0/d);
			if(z-a*i<=res+a&&z-a*i>=0)ans=max(ans,res+a);
		}
	}cout<<ans;
}
//>=(i+n)%n-d>=0
//d<=
//(p + n) * i + y + d = k
//p - y <= n - d
//p<={k-2d-n(i-1)}/(i+1)
//544844442 1235 5411 9548122188
//364776944

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void exgcd(ll a, ll b, ll& d, ll& x, ll& y){
  if(!b){d = a; x = 1; y = 0;}
  else {exgcd(b, a%b, d, y, x); y-=a/b*x;}
}

int main()
{
  ll n, l, r, k, x, y, x0, y0, d, z, ans = -1;
  cin >> n >> l >> r >> k;
  __int64 _n = n, _k = k;
  x = (r - l + 1 + n) % n;
  y = n - x;
  if(_n * _n < _k / _n){
    for(int a = 0; a <= x; a++)
      for(int b = 0; b <= y; b++){
        if((k-x-a) >= 0 && (k-x-a)%(a+b+n)==0) ans = max(ans, (ll)a+b);
        if(a && (k+1-x-a)>=0 && (k+1-x-a)%(a+b+n)==0) ans = max(ans, (ll)a+b);
      }
  }else {
    if(x <= k && k <= 2*x) ans = min(k - x + y + 1, n);
    int l = (k+1) / (2*n);
    int r = (k+1) / n;
    for(int t = max(l, 1); t <= r; t++){
      int rt = k - t*n - x;
      exgcd(t+1, t, d, x0, y0);
      for(int rest = rt; rest <= rt+1; rest++){
        if(rest % d == 0){
          x0 = rest / d * x0;
          y0 = rest / d * y0;
          ll z = (x0 - (x0 % t + t)%t)/t;
          x0 -= t * z;
          y0 += (t+1)*z;
          if(rest == rt && 0 <= y0 && y0 <= y) ans = max(ans, x0 + y0);
          if(rest != rt && x0 && 0 <= y0 && y0 <= y) ans = max(ans, x0 + y0);
          else{
            z = (y0 - y + t) / (t+1);
            x0 += t * z;
            y0 -= (t+1)*z;
            if(rest == rt && 0 <= x0 && x0 <= x) ans = max(ans, x0 + y0);
            if(rest != rt && x0 && 0 <= x0 && x0 <= x) ans = max(ans, x0 + y0);
          }
        }
      }
    }
  }
  cout << ans << endl;
  return 0;
}

#include <iostream>
#include <fstream>
using namespace std;

long long bs(long long t,long long l,long long r,long long h,long long x,long long n)
{
    long long mid,tp=-1;
    while (l<=r)
    {
        mid=(l+r)/2;
        if (mid<(t-mid*x) || (t-mid*x)>h) l=mid+1; else
        if (mid-(t-mid*x)<=n-h && (t-mid*x)<=h)
        {
            l=mid+1;
            tp=mid;
        } else r=mid-1;
    }
    return tp;
}

int main()
{
    //freopen("m.inp","r",stdin);
    //freopen("m.out","w",stdout);
    long long n,l,r,k,h,t,m2=-1;
    cin>>n>>l>>r>>k;
    if (r>=l) h=r-l+1; else h=n-l+1+r;
    if (n<=1000000)
    {
        for (int m=n;m>=1;m--)
        {
            t=k%(n+m);
            if ((t>=max(h,m-n+2*h) && t<=min(m+h,2*h)) || (t==0 && ((l==1 && r==n) || (l-1==r))))
            {
                m2=m;
                break;
            }
        }
        k=k+1;
        for (int m=n;m>=1;m--)
        {
            t=k%(n+m);
            if ((t>=max(h,m-n+2*h) && t<=min(m+h,2*h)) || (t==0 && ((l==1 && r==n) || (l-1==r))))
            {
                if (m>m2) m2=m;
                break;
            }
        }
        cout<<m2;
    }
    else
    {
        long long m3;
        if (k<=2*h) m2=k-h+(n-h);
        for (int i=1;i<=k/n;i++)
        {
            t=k-n*i-h;
            m3=bs(t,0,n,h,i,n);
            if (m3!=-1)
            {
                if (m3>m2) m2=m3;
                break;
            }
        }
        k=k+1;
        if (k<=2*h) m2=k-h+(n-h);
        for (int i=1;i<=k/n;i++)
        {
            t=k-n*i-h;
            m3=bs(t,0,n,h,i,n);
            if (m3!=-1)
            {
                if (m3>m2) m2=m3;
                break;
            }
        }
        cout<<m2;
    }
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define LL long long

LL n,l,r,k,ans;

LL f1(LL x,LL y){
	return x>=0 ? x/y : -(-x+y-1)/y;
}

LL f2(LL x,LL y){
	return x>=0 ? (x+y-1)/y : -(-x/y);
}

int main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	LL x=r-l+1;
	if (x<=0) x+=n;
	LL y=n-x;
	ans=-1;
	if (n<=(LL)cbrt(k)){
		for (LL a=0;a<=x;a++)
		  for (LL b=0;b<=y;b++){
		  	LL sum=a+b+x+y,b_=k-a-x;
		  	if (b_>=0 && b_%sum==0) ans=max(ans,a+b);
		  	if (a>0 && b_+1>=0 && (b_+1)%sum==0) ans=max(ans,a+b);
		  }
	}
	else{
		for (LL t=0;t<=k/n;t++){
			LL b_=k-n*t-x;
			if (t==0){
				if (b_<=x) ans=max(ans,b_+y);
				if (b_+1<=x) ans=max(ans,b_+1+y);
			}
			else{
				LL Min=max(f2(b_-x,t),f2(b_,t+1));
				LL Max=min(f1(b_,t),f1(b_+y,t+1));
				if (Max>=Min) ans=max(ans,Max);
				b_++;
				Min=max(f2(b_-x,t),f2(b_,t+1));
				Max=min(f1(b_-1,t),f1(b_+y,t+1));
				if (Max>=Min) ans=max(ans,Max);
			}
		}
	}
	printf("%lld\n",ans);
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int M = sqrt(1e11) + 4;

ll n, k, l, r, ans = -1;

void calcA(ll t, bool flag = false) {
    for (ll a = 0; a <= n; ++a) {
        ll gt = t / (a + n);
        for (int j = -1; j <= 1; ++j) {
            ll g = gt + j;
            if (g < 0) {
                continue;
            }
            ll ato = t - r - n * g - a * g;
            if (ato < 0 || ato > a || ato > r || (n - r) < a - ato || (flag && ato == 0)) {
                continue;
            }

            ans = max(ans, a);
        }
    }
}

void calcG(ll t, bool flag = false) {
    for (ll g = 1; g < M; ++g) {
        ll tg = t - n * g - r;
        if (tg < 0) {
            continue;
        }
        ll ag = tg / g;
        for (int j = -2; j <= 1; ++j) {
            ll a = ag + j;
            ll ato = tg - a * g;
            if (ato < 0 || ato > a || ato > r || (n - r) < a - ato || (flag && ato == 0)) {
                continue;
            }
            ans = max(ans, a);
        }
    }

    ll ato = t - r;
    ll a = n - r + ato;
    if (a < 0 || a > n || ato < 0 || ato > r || (n - r) < a - ato || (flag && ato == 0)) {
        return;
    }
    ans = max(ans, a);
}

void calcA() {
    calcA(k);
    calcA(k + 1, true);
}

void calcG() {
    calcG(k);
    calcG(k + 1, true);
}

void solve() {
    cin >> n >> l >> r >> k;
    l--, r--;
    r = (r - l + n) % n + 1;

    ///

    if (n < M) {
        calcA();
    } else {
        calcG();
    }

    cout << ans;
}

int main() {
    ios::sync_with_stdio(0);
    cout.tie(0), cin.tie(0);

    solve();

    return 0;
}

// I love meowmur
// We miss you, Arthur
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast", "unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define all(a) (a).begin(), (a).end()
#define sz(a) (ll)((a).size())
#define heap priority_queue
#define hash_map unordered_map
#define hash_set unordered_set
#define ft first
#define sd second
#define fast ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define endl "\n"
#define mineq(a, b) (a) = ((a)>(b))?(b):(a)
#define maxeq(a, b) (a) = ((a)<(b))?(b):(a)
#define die(cond) if (cond) for (;;){}
#define y1 y_1
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
typedef vector<ll> vll;
typedef set<ll> sll;
typedef map<ll, ll> mll;
const ll inf = numeric_limits<ll>::max() / 2;
const ld eps = 1e-9;
const ld pi = acos(-1);

inline void solve(), read();

int main() {
	fast;
	read();
	solve();
	return 0;
}

ll gcd(ll a, ll b) {
	while (b != 0) {
		a %= b;
		swap(a, b);
	}
	return a;
}
pll exgcd(ll a, ll b) {
	if (a == 0) {
		return { 0, 1 };
	}
	ll x0, y0;
	tie(x0, y0) = exgcd(b % a, a);
	ll x = y0 - b / a * x0;
	ll y = x0;
	return { x, y };
}

ll n, l, r, k;
ll x, y;

pll solve(ll a, ll b, ll c) {
	ll x, y;
	tie(x, y) = exgcd(a, b);
	ll g = gcd(a, b);
	if (c % g != 0) {
		return { -inf, -inf };
	}
	c /= g;
	x *= c, y *= c;
	return { x, y };
}

ll n2(ll f) {
	if (f) {
		++k;
	}
	ll ans = -1;
	for (ll a = 0; a <= x; a++) {
		for (ll b = (f && !a) ? 1 : 0; b <= y; b++) {
			if (x + y + a + b == 0) {
				continue;
			}
			if ((k - x - a) % (x + y + a + b) != 0) {
				continue;
			}
			ll t = (k - x - a) / (x + y + a + b);
			maxeq(ans, a + b);
		}
	}
	return ans;
}
ll nk(ll f) {
	if (f) {
		++k;
	}
	ll ans = -1;
	if (k - x <= x) {
		maxeq(ans, k - x + y);
	}
	for (ll t = 1; t <= k / n + 1; t++) {
		ll c = k - t * n - x;
		ll a, b;
		tie(a, b) = solve(t + 1, t, c);
		if (a == -inf) {
			continue;
		}
		a = (a % t + t) % t;
		b = (c - a * (t + 1)) / t;
		if (b > y) {
			ll diff = b - y;
			ll ch = (diff + t) / (t + 1);
			b -= ch * (t + 1);
			a += ch * t;
		}
		if (f && !a) {
			continue;
		}
		if (0 <= a && a <= x && 0 <= b && b <= y) {
			maxeq(ans, a + b);
		}
	}
	return ans;
}

inline void solve() {
	if (k < x) {
		cout << -1 << endl;
		return;
	}
	x = (r - l + n) % n + 1;
	y = n - x;
	ll ansk = -1, ansk1 = -1;
	if (0) {
		ansk = n2(0);
		ansk1 = n2(1);
	} else {
		ansk = nk(0);
		ansk1 = nk(1);
	}
	ll ans = max(ansk, ansk1);
	cout << ans << endl;
}

inline void read() {
	cin >> n >> l >> r >> k;
}

#include <algorithm>
#include <iostream>

#include <cmath>

using namespace std;

typedef long long ll;

int main(int argc, char *argv[]) {
#ifdef KANARI
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ll n, l, r, k;
	cin >> n >> l >> r >> k;
    ll first = (r - l + n) % n + 1;
    k -= first;
    ll threshold = static_cast<ll>(sqrt(k));
    ll max_t = (k + 1) / n;

    auto try_t = [&](ll k, ll t, bool allowZero) {
        ll rem = k - t * n;
        ll s1 = rem % t;
        ll s = (rem - (t + 1) * s1) / t + s1;
//        while (s1 <= first) {
//            if ((allowZero || s1 > 0) && (s - s1) <= (n - first))
//                return s;
//            s1 += t, s -= t;
//        }
        ll min_p = (first + s - n - s1 + (2 * t - 1)) / (2 * t);
        s1 += t * min_p;
        if ((allowZero || s1 > 0) && s1 <= first)
            return s - t * min_p;
        return -1LL;
    };

    auto try_s = [&](ll k, ll s, bool allowZero) {
        ll min_s1 = k % (s + n);
        if ((allowZero || min_s1 > 0) && min_s1 <= s && min_s1 <= first && (s - min_s1) <= (n - first))
            return s;
        return -1LL;
    };

    ll ans = -1LL;
    if (max_t < threshold) {
        // check for t = 0
        {
            ll min_s = k;
            if (min_s <= first) ans = max(ans, n - max(0LL, first - min_s - 1));
        }
        for (ll t = 1; t <= max_t; ++t) {
            ans = max(ans, try_t(k, t, true));
            ans = max(ans, try_t(k + 1, t, false));
        }
    } else {
        // n <= threshold
        for (ll s = 0; s <= n; ++s) {
            ans = max(ans, try_s(k, s, true));
            ans = max(ans, try_s(k + 1, s, false));
        }
    }

    cout << ans << endl;

	fclose(stdin);
	fclose(stdout);
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll n, x, k, lb, ub, ans = -1;

void init() {
    ll l, r;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    x = (r >= l ? r - l + 1 : r + n - l + 1) % n;
}

void solve() {
    for(ll i = k, j, r; i; i = j) {
        j = k / (k / i + 1); r = k / i;
        ub = min(2 * n, i);
        lb = max(n, j + 1);
        ub = min(ub, min((2 * n + k - 2 * x + 1) / (r + 1), (k - x) / r));
        lb = max(lb, (k - 2 * x) / r);
        if(ub >= lb) ans = max(ans, ub);
    }
    if(x <= k && k <= x * 2) ans = max(ans, n + min(k - x, x - 1) + n - x + 1);
    printf("%lld\n", ~ans ? ans - n : ans);
}

int main() {
    init();
    solve();
}

/*input

*/
#include <bits/stdc++.h>
#pragma GCC optimize("unroll-loops,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<double,double> pdd;
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#define ALL(a) a.begin(),a.end()
#define SZ(a) ((int)a.size())
#define F first
#define S second
#define REP(i,n) for(int i=0;i<((int)n);i++)
#define pb push_back
#define MP(a,b) make_pair(a,b)
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#ifdef leowang
#define debug(...) do{\
	fprintf(stderr,"%s - %d : (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
	_DO(__VA_ARGS__);\
}while(0)
template<typename I> void _DO(I&&x){cerr<<x<<endl;}
template<typename I,typename...T> void _DO(I&&x,T&&...tail){cerr<<x<<", ";_DO(tail...);}
#else
#define debug(...)
#endif
template<typename T1,typename T2>
ostream& operator<<(ostream& out,pair<T1,T2> P){
	out<<'('<<P.F<<','<<P.S<<')';
	return out;
}
//}}}
const ll maxn=300005;
const ll maxlg=__lg(maxn)+2;
const ll INF64=8000000000000000000LL;
const int INF=0x3f3f3f3f;
const ll MOD=ll(1e9+7);
const double PI=acos(-1);
//const ll p=880301;
//const ll P=31;

ll mypow(ll a,ll b){
	ll res=1LL;
	while(b){
		if(b&1) res=res*a%MOD;
		a=a*a%MOD;

		b>>=1;
	}
	return res;
}

const ll magic=300000;

int main()
{
	IOS;
	ll n,l,r,k;
	cin>>n>>l>>r>>k;
	ll ans=-1;
	if(n>magic){
		for(ll i=0;;i++){
			ll pp=i*n+(r-l)%n+1;
			ll tt=k-pp;
			if(tt>pp) continue;
			if(pp>k) break;

			if(i==0){
				ans=max(ans,n-pp+min(pp,tt+1));
				continue;
			}

			ll rem=(r-l)%n+1;
			ll numi=n-rem+1;
			ll plus=n-numi+1;
			ll grd=0;

			ll R=tt%i;
			tt-=R*(i+1);
			plus-=R;
			grd+=R;

			if(tt<0||plus<0) continue;

			tt/=i;
			if(tt<=numi){
				ans=max(ans,grd+tt);
			}
			else{
				ll dif=tt-numi;
				ll tm=(dif-1)/(i+1)+1;
				tt-=tm*(i+1);
				plus-=tm*i;
				grd+=tm*i;
				if(plus<0||tt<0) break;
				ans=max(ans,grd+tt);
			}
		}
		cout<<ans<<'\n';
	}
	else{
		{
			ll pp=(r-l)%n+1;
			ll tt=k-pp;
			if(tt<=pp&&pp<=k){
				ans=max(ans,n-pp+min(pp,tt+1));
			}
		}
		for(ll i=n;i>=0;i--){
			ll acycle=i+n;
			ll rem=(r-l)%n+1;
			if(rem==n){
				if(k%(i+n)==0||(k+1)%(i+n)==0){
					ans=max(ans,i);
					break;
				}
				continue;
			}
			ll cntC=k/acycle;
			ll lft=k-cntC*acycle;
			if(lft<rem||lft>2*rem) continue;
			lft-=rem;

			if(lft<=rem&&i-lft<=n-rem&&i-lft>=0){
				ans=max(ans,i);
				break;
			}
			if(lft!=rem&&lft+1<=rem&&i-lft-1<=n-rem&&i-lft-1>=0){
				ans=max(ans,i);
				break;
			}
		}
		cout<<ans<<'\n';
	}

	return 0;
}

#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")

#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/rope>

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

typedef long long ll;
typedef long double ld;
typedef complex<ld> cd;

typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;

typedef vector<int> vi;
typedef vector<ld> vd;
typedef vector<ll> vl;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<cd> vcd;

template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;

#define FOR(i, a, b) for (int i=a; i<(b); i++)
#define F0R(i, a) for (int i=0; i<(a); i++)
#define FORd(i,a,b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)

#define sz(x) (int)(x).size()
#define mp make_pair
#define pb push_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()

const int MOD = 1000000007;
const ll INF = 1e18;
const int MX = 100001;

/**
* Description: more convenient functions for input / output
  * experimentation with C++11 features
*/

namespace io {
    template<typename Test, template<typename...> class Ref>
    struct is_specialization : std::false_type {};

    template<template<typename...> class Ref, typename... Args>
    struct is_specialization<Ref<Args...>, Ref>: std::true_type {};
    // https://stackoverflow.com/questions/16337610/how-to-know-if-a-type-is-a-specialization-of-stdvector

    void setIn(string s) { freopen(s.c_str(),"r",stdin); }
    void setOut(string s) { freopen(s.c_str(),"w",stdout); }
    void setIO(string s = "") {
        ios_base::sync_with_stdio(0); cin.tie(0);
        if (sz(s)) { setIn(s+".in"), setOut(s+".out"); }
    }

    // INPUT

    // double input seems slow on CF
    void re(double& x) { string t; cin >> t; x = stod(t); }
    void re(ld& x) { string t; cin >> t; x = stold(t); }
    template<class T> void re(T& x) { cin >> x; }
    template<class Arg, class... Args> void re(Arg& first, Args&... rest) {
        re(first); re(rest...);
    }
    template<class T1, class T2> istream& operator>>(istream& is, pair<T1,T2>& p) {
        is >> p.f >> p.s; return is;
    }
    template<class T> istream& operator>>(istream& is, vector<T>& a) {
        F0R(i,sz(a)) is >> a[i];
        return is;
    }

    // OUTPUT

    template<class T> void pr(const T& x) { cout << x << '\n'; }
    template<class Arg, class... Args> void pr(const Arg& first, const Args&... rest) {
        cout << first << ' '; pr(rest...);
    }
    template<class T1, class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) {
        os << '{' << a.f << ", " << a.s << '}'; return os;
    }
    template<class T> ostream& operator<<(ostream& os, const vector<T>& a) {
        os << '{';
        F0R(i,sz(a)) {
            if (i) {
                os << ", ";
                if (is_specialization<T, vector>::value) os << '\n';
            }
            os << a[i];
        }
        os << '}';
        return os;
    }
}

using namespace io;

ll n,l,r,k, ans = -1;

void solve0() {
    if (r == k) ans = max(ans,n-r);
    ll t = k-r;
    for (ll i = 1; i*i <= t; ++i) if (t % i == 0) {
        ll x = i-n;
        if (0 <= x && x <= n-r) ans = max(ans,x);
        x = t/i-n;
        if (0 <= x && x <= n-r) ans = max(ans,x);
    }
}

void solve() {
    // prefix=k-r-c(n+x)
    FOR(x,1,min(n,1000000LL)+1) {
        ll lo = max(x-(n-r),1LL), hi = min((ll)x,r);
        ll clo = max(0LL,(ll)ceil((ld)(k-r-hi)/(n+x)));
        ll chi = floor((ld)(k-r-lo)/(n+x));
        if (clo <= chi) ans = max(ans,(ll)x);
    }
    // cout << ans << "\n";
    F0R(c,1000001) {
        // prefix = k-cn-r-cx

        // 1 <= x <= n
        ll lo = 1, hi = n;

        // k-cn-r-cx <= x --> x >= (k-cn-r)/(c+1)
        lo = max(lo,(ll)ceil((ld)(k-(ld)c*n-r)/(c+1)));

        // 1 <= k-cn-r-cx
        // k-cn-r-cx <= r --> cx >= k-cn-2r
        if (c == 0) {
            if (!(1 <= k-r)) continue;
            if (!(0 >= k-2*r)) continue;
        } else {
            hi = min(hi,(ll)floor((k-(ld)c*n-r-1)/c));
            lo = max(lo,(ll)ceil(k-(ld)c*n-2*r)/c);
        }

        // x-(n-r) <= k-cn-r-cx
        hi = min(hi,(ll)floor((k-(ld)c*n-r+n-r)/(c+1)));

        if (lo <= hi) ans = max(ans,hi);
    }
}

int main() {
    setIO(); re(n,l,r,k);
    r = r-l+1; if (r < 0) r += n;
    solve0();
    solve();
    k ++;
    solve();
    cout << ans;
}

/*
* (Actually read this pls)
    * Rlly bad errors: int overflow, array bounds
    * Less bad errors: special cases (n=1?), set tle
    * Common sense: do smth instead of nothing
*/

#include <bits/stdc++.h>
using namespace std;
#define FO(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout)
#define fo(i,j,k) for(int i=(j),end_i=(k);i<=end_i;i++)
#define ff(i,j,k) for(int i=(j),end_i=(k);i< end_i;i++)
#define fd(i,j,k) for(int i=(j),end_i=(k);i>=end_i;i--)
#define DEBUG(x) cout<<#x<<"="<<x<<endl
#define all(x) (x).begin(),(x).end()
#define cle(x) memset(x,0,sizeof(x))
#define lowbit(x) ((x)&-(x))
#define ll long long
#define ull unsigned ll
#define db double
#define lb long db
#define pb push_back
#define mp make_pair
#define fi first
#define se second

ll n,l,r,k,y,ans,x;
int main()
{
	cin>>n>>l>>r>>k;
	if(r>=l) r=r-l+1;
	else r=n-(l-r)+1;
	if(r==n) r=0;
	ans=-1;
	if(n<=1000000)
	{
		fo(i,0,n)
		{
			x=k/(n+i);
			y=k-(n+i)*x;
			if(y>=r&&y<=r*2&&(n+i)-2ll*(n-r)-1<=y&&y<=(n+i)-(n-r)) ans=max(ans,(ll)i);
		}
	}
	else
	{
		fo(i,1,k/n)
		{
			x=max((k-2ll*r)/i,(k+(n-r))/(i+1));
			y=min((k+1+2ll*(n-r))/(i+1),(k-r)/i);
			if(y>=x) ans=max(ans,y-n);
		}
		if(r<=k&&k<=2ll*r) ans=max(ans,(k==2ll*r)?n:((n-r)+(k-r)+1));
	}
	printf("%lld",ans);
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
long long i, j, k, n, l, r, d, p, a, b, c;

int main() {
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    //ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin >> n >> l >> r >> k;
    if (l > r)
        r += n;
    d = r - l + 1;
    p = n - d;
    if (n <= 1) {
        long long ans = -1;
        for (i = d; i <= 2 * d; ++i)
        for (j = p; j <= 2 * p; ++j)
        if ((k - i) % (i + j) == 0)
            ans = max(ans, i + j - n);
        for (i = d + 1; i <= 2 * d; ++i)
        for (j = p; j <= 2 * p; ++j)
        if ((k - i + 1) % (i + j) == 0)
            ans = max(ans, i + j - n);
        cout << ans;
    } else {
        long long ans = n - 1;
        if (k <= d)
            ans = k + 2 * p;
        for (c = 1; c <= k / n; ++c) {
            r = 2 * d;
            l = d;
            r = min(r, (k - p * c) / (c + 1));
            l = max(l, (k - 2 * c * p) / (c + 1));
            if ((k - l) / c - l < 2 * p)
                ++l;
            long long x;
            if (l % c  <= k % c)
                x = (l / c) * c + k % c;
            else
                x = (l / c + 1) * c + k % c;
            cout << l << endl;
            if (x >= l)
                ans = max(ans, (k - x) / c);
        }
        for (i = d + 1; i <= 2 * d; ++i)
        for (j = p; j <= 2 * p; ++j)
        if ((k - i + 1) % (i + j) == 0)
            ans = max(ans, i + j);
        cout << ans - n;
    }
}

#pragma GCC optimize("O3")
#ifdef ONLINE_JUDGE
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#endif
#pragma GCC optimize("unroll-loops")
#pragma comment(linker, "/stack:200000000")
#include <bits/stdc++.h>
#include <type_traits>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
template<typename Key=int,typename Mapped=__gnu_pbds::null_type,typename Cmp_Fn=std::less<Key>,typename Tag=__gnu_pbds::rb_tree_tag,template<typename Const_Node_Iterator,typename Node_Iterator,typename Cmp_Fn_,typename Allocator_>class Node_Update=__gnu_pbds::tree_order_statistics_node_update,typename Allocator=std::allocator<char>>class ordered_set_t:__gnu_pbds::tree<Key,Mapped,Cmp_Fn,Tag,Node_Update,Allocator>{};const int GRANDOM=std::chrono::high_resolution_clock::now().time_since_epoch().count();struct ghash{int operator()(int x){return std::hash<int>{}(x^GRANDOM);}};template<typename KeyType>class hash_table_t:__gnu_pbds::gp_hash_table<KeyType,int,ghash>{};namespace vh{template<class T>void _R(T&x){std::cin>>x;}inline void _R(int&x){scanf("%d",&x);}inline void _R(int64_t&x){scanf("%" SCNd64,&x);}inline void _R(double&x){scanf("%lf",&x);}inline void _R(char&x){scanf(" %c",&x);}inline void _R(char*x){scanf("%s",x);}inline void R(){}template<class T,class... U>inline void R(T&head,U&... tail){_R(head);R(tail...);}template<class T>void _W(const T&x){cout<<x;}inline void _W(const int&x){printf("%d",x);}inline void _W(const int64_t&x){printf("%" PRId64,x);}inline void _W(const double&x){printf("%.16f",x);}inline void _W(const char&x){putchar(x);}inline void _W(const char*x){printf("%s",x);}template<class T>inline void _W(const vector<T>&x){for(auto i=x.begin();i!=x.end();_W(*i++))if(i!=x.cbegin())putchar(' ');}inline void W(){}template<class T,class... U>inline void W(const T&head,const U&... tail){_W(head);if(sizeof...(tail))putchar(' '),W(tail...);}template<class T,class... U>inline void WL(const T&head,const U&... tail){_W(head);putchar(sizeof...(tail)? ' ':'\n');W(tail...);}};
#define prec setprecision
namespace vh{typedef long long ll;typedef unsigned long long llu;template<typename T>T gcd(T m,T n){while(n){T t=m%n;m=n;n=t;};return m;}template<typename T>T exgcd(T a,T b,T&sa,T&ta){T q,r,sb=0,tb=1,sc,tc;sa=1,ta=0;if(b)do q=a/b,r=a-q*b,a=b,b=r,sc=sa-q*sb,sa=sb,sb=sc,tc=ta-q*tb,ta=tb,tb=tc;while(b);return a;}template<typename T>T mul_inv(T a,T b){T t1=a,t2=b,t3;T v1=1,v2=0,v3;T x;while(t2!=1)x=t1/t2,t3=t1-x*t2,v3=v1-x*v2,t1=t2,t2=t3,v1=v2,v2=v3;return(v2+b)%b;}template<typename T>T powmod(T a,T b,T MOD){if(b<0)return 0;T rv=1;while(b)(b%2)&&(rv=(rv*a)%MOD),a=a*a%MOD,b/=2;return rv;}template<typename T>inline T isqrt(T k){T r=sqrt(k)+1;while(r*r>k)r--;return r;}template<typename T>inline T icbrt(T k){T r=cbrt(k)+1;while(r*r*r>k)r--;return r;}template<typename T>bool mul_overflow(T&r,T a,T b){return __builtin_mul_overflow(a,b,&r);}template<ll n>struct BitSize{enum{Size=BitSize<n/2>::Size+1};};template<>struct BitSize<0>{enum{Size=1};};template<>struct BitSize<1>{enum{Size=1};};
#define BITSIZE(n) (BitSize<n>::Size)
#define BITMAX(n) (BitSize<n>::Size - 1)
#define DEBUG !defined(ONLINE_JUDGE)
#define SZ(x) ((int)(x).size())
#define ALL(x) begin(x), end(x)
template<typename TH>void _dbg(const char*sdbg,TH h){cerr<<sdbg<<"="<<h<<"\n";}template<typename TH,typename... TA>void _dbg(const char*sdbg,TH h,TA... t){while(*sdbg!=',')cerr<<*sdbg++;cerr<<"="<<h<<",";_dbg(sdbg+1,t...);}
#ifdef DEBUG
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; for(auto itt: x) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
}namespace vh{template<typename T>int min_rotation(vector<T>s){int a=0,N=s.size();for(int b=0;b<N;b++)for(int i=0;i<N;i++){if(a+i==b||s[(a+i)%N]<s[(b+i)%N]){b+=max(0,i-1);break;}if(s[(a+i)%N]>s[(b+i)%N]){a=b;break;}}return a;}}namespace vh{};
namespace vh{
  int brute(int n,int l,int r,int k,bool with_last){
    int p=l<=r ?(r-l+1):(n+2-(l-r+1));
    int best=-1;
    if(p<=k&&k<=p*2){
      if(!with_last){
        best=max(best,min(p,k-p+1)+(n-p));
      }else{
        best=max(best,(k-p)+(n-p));
      }
    }
    for(int s=n;s<=k;s++){
      int a,b;
      if(k%s==0)a=s,b=0;
      else a=k%s,b=s-a;
      if(
          (with_last ?(p<a):(p<=a))&&a<=p*2
          &&(n-p)<=b&&b<=(n-p)*2
      ){
        best=max(best,s-n);
      }
    }
    return best;
  }
  ll solve(ll n,ll l,ll r,ll k,bool with_last){
    ll p=l<=r ?(r-l+1):(n+2-(l-r+1));
    ll best=-1;
    if(p<=k&&k<=p*2){
      if(!with_last)best=max(best,min(p,k-p+1)+(n-p));
      else best=max(best,(k+1-p)+(n-p));
    }
    ll q=n-p;
    ll amin=max(1ll,max(with_last?(p+1):(p),k/2-q));
    ll amax=min(p*2,(k-q)/2);
    if(amin<=amax){
      best=max(best,min(n,k-amin-n));
    }
    return best;
  }
  int main(){
    srand(GRANDOM);
    ll n,l,r,k;
    cin>>n>>l>>r>>k;
    cout<<max(
      solve(n,l,r,k,false),
      solve(n,l,r,k,true)
    )<<endl;
    return 0;
  }
};
int main(int argc,char*argv[]){
  std::cin.sync_with_stdio(false);std::cin.tie(nullptr);
  return vh::main();
}

/* cerberus97 - Hanit Banga */

#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>

using namespace std;

#define pb push_back
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;

const int N = 1e5 + 10;
const ll inf = 1e18;

void solve1(ll n, ll r, ll k);
void solve2(ll n, ll r, ll k) ;
ll maximize(ll a, ll c, ll d1, ll d2);

int main() {
	fast_cin();
	ll n, l, r, k;
	cin >> n >> l >> r >> k;
	r -= l - 1;
	if (r < 1) {
		r += n;
	}
	if (ld(n) * n <= k / n) {
		solve1(n, r, k);
	} else {
		solve2(n, r, k);
	}
}

void solve1(ll n, ll r, ll k) {
	ll best = -1;
	for (ll s1 = 0; s1 <= r; ++s1) {
		for (ll s2 = 0; s2 <= n - r; ++s2) {
			ll num = k - r - s1;
			ll den = s1 + s2 + n;
			if (num % den == 0) {
				ll a = num / den;
				if (a >= 0 and a * n <= k) {
					best = max(best, s1 + s2);
				}
			}
			if (s1 == 0) {
				continue;
			}
			++num;
			if (num % den == 0) {
				ll a = num / den;
				if (a >= 0 and a * n <= k) {
					best = max(best, s1 + s2);
				}
			}
		}
	}
	cout << best << endl;
}

void solve2(ll n, ll r, ll k) {
	ll a_mx = k / n, best = -1;
	for (ll a = 0; a <= a_mx; ++a) {
		best = max(best, maximize(a, k - r - a * n, n - r, r));
		best = max(best, 1 + maximize(a, k - r - a * n - a, n - r, r - 1));
	}
	cout << best << endl;
}

// Maximize x + y when ax + (a + 1)y = c, subject to 0 <= x <= d1 and 0 <= y <= d2
ll maximize(ll a, ll c, ll d1, ll d2) {
	if (a == 0) {
		return ((0 <= c and c <= d2) ? d1 + c : -inf);
	}
	ll x = ((-c % (a + 1)) + (a + 1)) % (a + 1);
	ll i = (d1 - x) / (a + 1);
	x += i * (a + 1);
	if (0 <= x and x <= d1) {
		ll y = (c - a * x) / (a + 1);
		if (0 <= y and y <= d2) {
			return x + y;
		}
	}
	return -inf;
}

#include<bits/stdc++.h>
#define reg register int
#define il inline
#define fi first
#define se second
#define mk(a,b) make_pair(a,b)
#define numb (ch^'0')
#define pb push_back
#define solid const auto &
#define enter cout<<endl
#define pii pair<int,int>
using namespace std;
#define int long long
typedef long long ll;
template<class T>il void rd(T &x){
    char ch;x=0;bool fl=false;
    while(!isdigit(ch=getchar()))(ch=='-')&&(fl=true);
    for(x=numb;isdigit(ch=getchar());x=x*10+numb);
    (fl==true)&&(x=-x);
}
template<class T>il void output(T x){if(x/10)output(x/10);putchar(x%10+'0');}
template<class T>il void ot(T x){if(x<0) putchar('-'),x=-x;output(x);putchar(' ');}
template<class T>il void prt(T a[],int st,int nd){for(reg i=st;i<=nd;++i) ot(a[i]);putchar('\n');}

namespace Miracle{
ll n,l,r,k;
ll len;
ll che(ll i,ll M){
    // cout<<" che "<<i<<" "<<M<<endl;
    ll ret=-1;
    if(i==0){
        ll p=M;
        if(p<=len) ret=max(ret,p);
        p=M+1;
        if(p>=1&&p<=len) ret=max(ret,p);
    }
    else{
        ll p=M%i;
        ll ans=(M-p)/i;
        if(ans>n) {
            p+=(ans-n)*i;
            ans=n;
        }
        if(p>=0&&p<=min(ans,len)) ret=max(ret,ans);

        p=(M+1)%i;
        ans=(M+1-p)/i;
        if(ans>n){
            p+=(ans-n)*i;
            ans=n;
        }
        if(p>=1&&p<=min(ans,len)) ret=max(ret,ans);
    }
    return ret;
}
int main(){
    rd(n);rd(l);rd(r);rd(k);
    if(l<=r) len=r-l+1;
    else len=n-l+1+r;
    if(n<=2e6){
        ll ans=0;
        for(ans=n;ans>=0;--ans){
            ll r=k%(ans+n);
            if(r==0) r+=ans+n;
            int p=r-len;
            if(p>=max((ll)0,ans-(n-len))&&p<=min(ans,len)) break;
            r=(k+1)%(ans+n);
            p=r-len;
            if(p>=max((ll)1,ans-(n-len))&&p<=min(ans,len)) break;
        }
        if(ans>=0) printf("%lld",ans);
        else printf("-1");
    }else{
        ll M=k-len;
        ll ans=-1;
        for(ll i=0;M>=0;++i,M-=n){
            ll ret=che(i,M);
            ans=max(ans,ret);
        }
        printf("%lld",ans);
    }
    return 0;
}

}
signed main(){
	Miracle::main();
	return 0;
}

/*
   Author: *Miracle*
*/

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

ll n,l,r,k,ans=-1;

int main()
{
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	ll acid=l<=r?r-l+1:n-l+1+r;
	if(n<=2e6)
	{
		for(ll mid=0;mid<=n;++mid)
		{
			ll kt=(k-acid)/(n+mid);
			ll value=k-kt*(n+mid)-acid;
			if(value>=0&&value<=min(acid,mid)&&mid-value<=n-acid+(value!=acid))
				ans=max(ans,mid);
		}
	}
	else
	{
		for(ll mid=0;mid<=k/n;++mid)
		{
			ll x=mid?(k-acid-mid*n)/mid:n+k-2*acid+(k!=2*acid);
			ll t=k-mid*(x+n)-acid;
			if(t>x)
			{
				ll bt=ceil(1.0*(t-x)/(mid-1));
				t-=bt*mid; x-=bt;
			}
			if(t>=0&&t<=acid&&x-t<=n-acid+(t!=acid))
				ans=max(ans,x);
		}
	}
	printf("%lld",ans);
	return 0;
}

#include <bits/stdc++.h>
#define mp make_pair
#define X first
#define Y second
#define pii pair<ll,ll>
#define x1 dlfjl
#define x2 dkfj
#define x3 dflgkg
#define y1 dskgj
#define y2 dskfj
#define y3 dfhgdh
#define SQ 320
#define PI 3.14159265359
#define MOD 1000000007
#define MAXN 1000005
typedef long long ll;
using namespace std;
ll i,j,k,z,q,timer,x,y,n,m, cnt, even, flag, x1,y1,x2,y2, boom,r,c;
vector<pii> f, f1;
ll solve(ll n, ll l, ll r, ll k, ll id) {
    ll C1 = 2*(r-l+1)-k;
    ll C2 = k - (r-l+1);
    ll m1 = -C1/(2*n) - 5;
    ll m2 = C2/n - 5;
    //cout << C1 << " " << C2 << endl;
    while (2*m1*n + C1 < 0)
        m1++;
    while (C2 - m2*n - n >= 0)
        m2++;
    //cout << m1 << " " << m2 << endl;
    if (m1 > m2) {
        return -1;
    }

    ll ans = -1;
    if (m1 == 0) {
        ll diff = k-(r-l+1);
        if (diff >= id && diff <= r-l+1)
            ans = diff + n-(r-l+1);
        m1++;
    }
    //cout << m1 << " " << m2 << endl;
    for (ll i = m1; i <= m2; i++) {
        ll T = k - (r-l+1);
        ll x, y;
        ll K = (T/i - T%i - 2*n + (r-l+1))/(i+1);
        y = T/i-K-T%i-i*K - n;
        x = (T - y*i - n*i)/(i+1);
        if (x >= id && x <= r-l+1 && y >= 0 && y <= n-(r-l+1))
            ans = max(ans, x+y);
    }

    return ans;
}
int main() {
    //freopen("input.txt", "r", stdin);
    ll n, l, r, k;
    cin >> n >> l >> r >> k;
    if (l > r) {
        r += n;
    }
    if (n >= 10000) {
        ll ans1 = solve(n,l,r,k,0);
        ll ans2 = solve(n,l,r,k+1,1);
    //cout << ans1 << " " << ans2 << endl;
        cout << max(ans1, ans2) << endl;
    } else {
        ll ans = -1;
        for (int i = 0; i <= r-l+1; i++)
            for (int j = 0; j <= n-(r-l+1); j++)
                if (k-(r-l+1)-i >= 0 && (k-(r-l+1)-i)%(i+j+n) == 0) {
                    ans = max(ans, 0LL+i+j);
                }
        k++;
        for (int i = 1; i <= r-l+1; i++)
            for (int j = 0; j <= n-(r-l+1); j++)
                if (k-(r-l+1)-i >= 0 && (k-(r-l+1)-i)%(i+j+n) == 0) {
                    ans = max(ans, 0LL+i+j);
                }
        cout << ans << endl;
    }
    return 0;
}

#include<bits/stdc++.h>
#define fo(i,a,b) for(i=a;i<=b;i++)
#define fd(i,a,b) for(i=a;i>=b;i--)
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
using namespace std;
typedef long long ll;
ll n,l,r,k,a,x,y,ans,K,t,z1,z2;
int main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	a=r-l+1,a+=a<=0?n:0,k-=a;
	ans=-1;
	if (k<0) return puts("-1"),0;
	if (k<=a) return printf("%lld\n",min(k+1,a)+n-a),0;
	if (n<=pow(k,1.0/3)){
		fo(x,0,a){
			K=k-x;
			fd(y,n-a,0){
				if (K%(n+x+y)==0&&(x&&(K+1)%(n+x+y)==0)) ans=max(ans,x+y);
				if (ans>=x+y) break;
			}
		}return printf("%lld\n",ans),0;
	}
	fo(t,1,k/n){
		K=k-t*n;
		z1=K<=a?0:(K-a-1)/t+1,z1=max(z1,(K-1)/(t+1)+1),z2=min(K/t,(n-a+K)/(t+1));
		if (z1<=z2) ans=max(ans,z2);
		K++;
		z1=K<=a?0:(K-a-1)/t+1,z1=max(z1,(K-1)/(t+1)+1),z2=min((K-1)/t,(n-a+K)/(t+1));
		if (z1<=z2) ans=max(ans,z2);
	}return printf("%lld\n",ans),0;
}

#include <bits/stdc++.h>

#define For(i, j, k) for (int i = j; i <= k; i++)
#define Forr(i, j, k) for (int i = j; i >= k; i--)

using namespace std;

typedef long long LL;

const LL lim = 1e7;

LL n, k, l, r;

int main() {

	cin >> n >> l >> r >> k;
	r = (r - l + n + 1) % n;
	if (!r) r = n;

	if (n <= lim) {
		Forr(i, n, 0) {
			int rb = min(r, LL(i)), lb = max(0ll, i - (n - r) - 1);
			LL tmp = (n + i) * 100ll;
			if ((k - lb - r + tmp) / (n + i) > (k - rb - 1 - r + tmp) / (n + i)) {
				cout << i << endl;
				return 0;
			}
		}
		cout << -1 << endl;
	} else {
		LL ans = -1;
		For(i, 0, k / n) {
			LL L = 0, R = n;
			while (L <= R) {
				LL mid = (L + R) / 2;
				LL rb = min(r, mid), lb = max(0ll, mid - (n - r) - 1);
				LL re = k - r - i * (n + mid);
				if (re > rb) L = mid + 1;
				else if (re < lb) R = mid - 1;
				else {
					L = mid + 1;
					ans = max(ans, mid);
				}
			}
		}
		cout << ans-1 << endl;
	}

	return 0;
}

#include<bits/stdc++.h>
#define scf scanf
#define ptf printf
#define forup(i,a,b) for(register ll i=a;i<=b;i++)
#define fordown(i,a,b) for(register ll i=a;i>=b;i--)
#define max(a,b) (((a)>(b))?(a):(b))
#define min(a,b) (((a)>(b))?(b):(a))
#define ll long long
#define mst(a,b) memset(a,b,sizeof a)
//#undef
using namespace std;
ll n,l,r,k;
ll d;
ll answer=-1;
inline int read(){
    int x=0,f=1;
    char ch=getchar();
    while(!isdigit(ch)){
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(isdigit(ch)){
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*f;
}
inline void charlotte(){
	if(n<2e6+5){
		 fordown(ans,n,0) {
            ll y=(k-1)%(n+ans)+1-d;
            if (y<0||y>ans||y>d||d-(y+1)>n-ans)
                continue;
            ll y_=y+1;
            if(y_<=ans&&y_<=d){
                answer=max(answer,ans);
            }
            if(d-y<=n-ans){
                answer=max(answer, ans);
            }
        }
	}
	else{
		forup(i,0,k/n) {
            ll ans=(k-2*d-(i-1)*n+1)/(i+1);
            ll y=k-i*(n+ans)-d;
            if(y<0){
                if(i==0)
                    continue;
                ll dis=(-y-1)/i+1;
                y+=i*dis;
                ans-=dis;
            }
            if(ans>n) {
                y+=(ans-n)*i;
                ans==n;
            }
            if(y<0||y>ans||y>d||d-(y+1)>n-ans)
                continue;
            ll y_=y+1;
            if(y_<=ans&&y_<=d)
                answer=max(answer,ans);
            if(d-y<=n-ans){
                answer=max(answer,ans);
            }
        }
	}
}
int main(){
    n=read(),l=read(),r=read(),k=read();
	d=(r-l+n)%n+1;
    charlotte();
    ptf("%lld\n",answer);
    return 0;
}

#include<bits/stdc++.h>
#define ll long long
#define ull unsigned ll
#define uint ungigned
#define db double
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pli pair<ll,int>
#define vi vector<int>
#define vpi vector<pii >
#define IT iterator

#define PB push_back
#define MK make_pair
#define LB lower_bound
#define UB upper_bound
#define y1 wzpakking
#define fi first
#define se second
#define BG begin
#define ED end

#define For(i,j,k) for (int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for (int i=(int)(j);i>=(int)(k);i--)
#define UPD(x,y) (((x)+=(y))>=mo?(x)-=mo:233)
#define CLR(a,v) memset(a,v,sizeof(a))
#define CPY(a,b) memcpy(a,b,sizeof(a))
#define sqr(x) (1ll*x*x)

#define LS3 k*2,l,mid
#define RS3 k*2+1,mid+1,r
#define LS5 k*2,l,mid,x,y
#define RS5 k*2+1,mid+1,r,x,y
#define GET pushdown(k);int mid=(l+r)/2
#define INF (1<<29)
using namespace std;
ll n,l,r,k,ans=-1;
void checkok(ll val2,ll val1,ll fi,ll se,ll pre){
	val2=val2-val1;
	se=se-fi;
	if (!(fi+pre<=val1&&val1<=2*fi)) return;
	if (!(se<=val2&&val2<=2*se)) return;
	ans=max(ans,val1+val2-fi-se);
}
void check1(ll val){
	checkok(val,(k+val-1)%val+1,r,n,0);
	checkok(val,k%val+1,r,n,1);
}
pll getrange(ll lv,ll k,ll mv,ll rv){
	lv-=mv; rv-=mv;
	if (!k){
		if (lv<=0&&rv>=0) return pll(0,1ll<<60);
		return pll(-1,-1);
	}
	if (k<0){
		swap(lv,rv);
		lv=-lv; rv=-rv;
		k=-k;
	}
	if (rv<0) return pll(-1,-1);
	if (lv<0) lv=max(lv,0ll);
	return pll((lv+k-1)/k,rv/k);
}
pll merge(pll a,pll b){
	if (a.fi==-1||b.fi==-1) return pll(-1,-1);
	if (a.se>b.se) swap(a,b);
	if (a.se<b.fi) return pll(-1,-1);
	return pll(max(a.fi,b.fi),a.se);
}
void check2(ll round){
	if (round==0){
		if (r<=k&&k<=2*r) ans=max(ans,n-r);
		if (r+1<=k+1&&k+1<=2*r) ans=max(ans,n-r+1);
		return;
	}
	ll r=min(k/round,2*n);
	ll l=max(k/(round+1)+1,n);
	ll fi=::r,se=n-::r;
	if (l<=r){
		pll range1=getrange(fi+1,-round,k+1,2*fi);
		pll range2=getrange(se,round+1,-k-1,2*se);
		pll range=merge(pll(l,r),merge(range1,range2));
		if (range.fi!=-1) ans=max(ans,range.se-n);
	}
	r=min((k-1)/round,2*n);
	l=max((k-1)/(round+1)+1,n);
	if (l<=r){
		pll range1=getrange(fi,-round,k+1,2*fi);
		pll range2=getrange(se,round+1,-k-1,2*se);
		pll range=merge(pll(l,r),merge(range1,range2));
		if (range.fi!=-1) ans=max(ans,range.se-n);
	}
}
//checkok(val,k-round*val+1,r,n,1)
//val2=(round+1)*val-k-1
//val1=k-round*val+1
//fi+1<=round<=2*fi
//se<=
int main(){
	scanf("%lld%lld%lld%lld",&n,&l,&r,&k);
	r=(r-l+n)%n+1;
	if (n<=200000)
		for (ll i=n;i<=2*n;i++) check1(i);
	else
		for (ll round=k/(2*n);round<=k/n;round++)
			check2(round);
	printf("%lld",ans);
}

#include<bits/stdc++.h>
#define reg register int
#define il inline
#define fi first
#define se second
#define mk(a,b) make_pair(a,b)
#define numb (ch^'0')
#define pb push_back
#define solid const auto &
#define enter cout<<endl
#define pii pair<int,int>
using namespace std;
#define int long long
typedef long long ll;
template<class T>il void rd(T &x){
    char ch;x=0;bool fl=false;
    while(!isdigit(ch=getchar()))(ch=='-')&&(fl=true);
    for(x=numb;isdigit(ch=getchar());x=x*10+numb);
    (fl==true)&&(x=-x);
}
template<class T>il void output(T x){if(x/10)output(x/10);putchar(x%10+'0');}
template<class T>il void ot(T x){if(x<0) putchar('-'),x=-x;output(x);putchar(' ');}
template<class T>il void prt(T a[],int st,int nd){for(reg i=st;i<=nd;++i) ot(a[i]);putchar('\n');}

namespace Miracle{
ll n,l,r,k;
ll len;
ll che(ll i,ll M){
    // cout<<" che "<<i<<" "<<M<<endl;
    ll ret=-1;
    if(i==0){
        ll p=M;
        if(p<=len) ret=max(ret,p+n-len);
        p=M+1;
        if(p>=1&&p<=len) ret=max(ret,p+n-len);
    }
    else{
        ll p=M%i;
        ll ans=(M-p)/i;
        if(ans>n) {
            p+=(ans-n)*i;
            ans=n;
        }
        if(p>=0&&p<=min(ans,len)) ret=max(ret,ans);

        p=(M+1)%i;
        ans=(M+1-p)/i;
        if(ans>n){
            p+=(ans-n)*i;
            ans=n;
        }
        if(p>=1&&p<=min(ans,len)) ret=max(ret,ans);
    }
    return ret;
}
int main(){
    rd(n);rd(l);rd(r);rd(k);
    if(l<=r) len=r-l+1;
    else len=n-l+1+r;
    // cout<<" len "<<len<<endl;
    if(n<=2e6){
        ll ans=0;
        for(ans=n;ans>=0;--ans){
            ll r=k%(ans+n);
            if(r==0) r+=ans+n;
            int p=r-len;
            if(p>=max((ll)0,ans-(n-len))&&p<=min(ans,len)) break;
            r=(k+1)%(ans+n);
            p=r-len;
            if(p>=max((ll)1,ans-(n-len))&&p<=min(ans,len)) break;
        }
        if(ans>=0) printf("%lld",ans);
        else printf("-1");
    }else{
        ll M=k-len;
        ll ans=-1;
        for(ll i=0;M>=0;++i,M-=n){
            ll ret=che(i,M);
            ans=max(ans,ret);
        }
        printf("%lld",ans);
    }
    return 0;
}

}
signed main(){
	Miracle::main();
	return 0;
}

/*
   Author: *Miracle*
*/

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main() {
    ll n, l, r, k;
    cin >> n >> l >> r >> k;
    ll p = (l <= r) ? r - l + 1 : r + n - l + 1;
    if (n < 1e6) {
        int c;
        for (c = n; c >= 0; c --) {
            ll m = (k - 1) % (n + c) + 1;
            if (m <= min(c + p, 2 * p) && m >= max(p, 2 * p + c - n - 1)) break;
        }
        printf("%d\n", c);
    }
    else {
        ll ans = n - 1;
        for (int d = 1; d < 1e6; d ++) {
            r = min(2 * n, min((k - p) / d, (k + 2 * n + 1 - 2 * p) / (d + 1)));
            l = max(n, max((k - 2 * p - 1) / d, (k + n - p - 1) / d) + 1);
            if (r >= l) ans = max(ans, r);
        }
        printf("%I64d\n", ans - n);
    }
}

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <tuple>
#include <iterator>
#include <cmath>

using namespace std;

const int THR = 5000;

int main()
{
    //freopen("in", "r", stdin);
    //freopen("out", "w", stdout);

    long long n, l, r, k;
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);

    long long d = r - l + 1;
    while(d <= 0)
        d += n;

    if(k < d)
    {
        puts("-1");
        return 0;
    }

    long long res = -1;
    if(n < THR)
    {
        for(long long i = 0; i <= d; i++)
        {
            for(long long j = 0; j <= (n - d); j++)
            {
                long long t = k - (d + i);
                if(t == 0 || i > 0 && t == -1)
                {
                    res = max(res, i + j);
                    continue;
                }

                long long q = t / (n + i + j);
                long long t2 = t - q * (n + i + j);
                if(q >= 0 && (t2 == 0 || i > 0 && t2 == -1))
                {
                    res = max(res, i + j);
                    continue;
                }

                long long t3 = t - (q + 1) * (n + i + j);
                if(q + 1 >= 0 && (t3 == 0 || i > 0 && t3 == -1))
                {
                    res = max(res, i + j);
                    continue;
                }
            }
        }
    }
    else
    {
        long long s, g;
        s = max(0LL, (k / 2 - d) / n - 10);
        g = max(s, (k - d) / n + 10);

        for(long long i = s; i <= g; i++)
        {
            if(k < d + n * i)
                continue;

            if(k > 2 * (d + n * i))
                continue;

            if(i == 0)
            {
                res = max(res, min(d, k + 1 - d) + n - d);
                continue;
            }

            {
                long long t = k - (d + n * i);

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(q >= 0 && r1 == 0)
                            res = max(res, n - d + min(d, q));
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(q >= 0 && r1 == 0)
                            res = max(res, min(n - d, q));
                    }
                }
            }

            {
                long long t = k + 1 - (d + n * i);
                t -= i + 1;

                if(t - (n - d) * i >= 0)
                {
                    t -= (n - d) * i;
                    if(t >= 0)
                    {
                        long long q = t / (i + 1);
                        long long r1 = t - q * (i + 1);
                        if(q >= 0 && r1 == 0)
                            res = max(res, n - d + min(d, q + 1));
                    }
                }
                else
                {
                    if(t >= 0)
                    {
                        long long q = t / i;
                        long long r1 = t - q * i;
                        if(q >= 0 && r1 == 0)
                            res = max(res, min(n - d, q + 1));
                    }
                }
            }
        }
    }

    printf("%lld\n", res);
    return 0;
}

#include <cstdio>
#include <cstring>
#include <algorithm>
#define int long long

using namespace std;

const int Lim = 1000000;

int n, l, r, k;

int bigeq(int x, int y) {
    int tmp = x / y;
    while(tmp * y < x) tmp++;
    while((tmp - 1) * y >= x) tmp--;
    return tmp;
}

int smalleq(int x, int y) {
    int tmp = x / y;
    while(tmp * y > x) tmp--;
    while((tmp + 1) * y <= x) tmp++;
    return tmp;
}

signed main() {
    scanf("%lld%lld%lld%lld", &n, &l, &r, &k);
    r = (r + n - l) % n + 1;
    int ans = -1;
    // Case 2
    for(int i = 0; i <= Lim; i++) {
        int l = max(r, r + r + i - n - 1), r = min(r + r, r + i);
        if(k % (i + n) <= r && k % (i + n) >= l || k % (i + n) + n <= r && k % (i + n) + n >= l) ans = i;
    }
    // Case 1
    for(int t = 0; t <= Lim; t++) {
        int k = ::k - t * n;
        int r1 = !t ? (k - r >= 0 ? n : -1) : smalleq(k - r, t);
        int r2 = smalleq(k + n + 1 - r - r, t + 1);
        int l1 = !t ? (k - r - r <= 0 ? 0 : n + 1) : bigeq(k - r - r, t);
        int l2 = bigeq(k - r, t + 1);
        if(max(l1, l2) <= min(r1, r2)) ans = max(ans, min(r1, r2));
    }
    printf("%lld\n", ans);
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#define ms(s, n) memset(s, n, sizeof(s))
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define FORd(i, a, b) for (int i = (a) - 1; i >= (b); --i)
#define FORall(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
#define sz(a) int((a).size())
#define present(t, x) (t.find(x) != t.end())
#define all(a) (a).begin(), (a).end()
#define uni(a) (a).erase(unique(all(a)), (a).end())
#define pb push_back
#define pf push_front
#define mp make_pair
#define fi first
#define se second
#define prec(n) fixed<<setprecision(n)
#define bit(n, i) (((n) >> (i)) & 1)
#define bitcount(n) __builtin_popcountll(n)
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<pi> vii;
const int MOD = (int) 1e9 + 7;
const int FFTMOD = 119 << 23 | 1;
const int INF = (int) 1e9 + 23111992;
const ll LINF = (ll) 1e18 + 23111992;
const ld PI = acos((ld) -1);
const ld EPS = 1e-9;
inline ll gcd(ll a, ll b) {ll r; while (b) {r = a % b; a = b; b = r;} return a;}
inline ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
inline ll fpow(ll n, ll k, int p = MOD) {ll r = 1; for (; k; k >>= 1) {if (k & 1) r = r * n % p; n = n * n % p;} return r;}
template<class T> inline int chkmin(T& a, const T& val) {return val < a ? a = val, 1 : 0;}
template<class T> inline int chkmax(T& a, const T& val) {return a < val ? a = val, 1 : 0;}
inline ull isqrt(ull k) {ull r = sqrt(k) + 1; while (r * r > k) r--; return r;}
inline ll icbrt(ll k) {ll r = cbrt(k) + 1; while (r * r * r > k) r--; return r;}
inline void addmod(int& a, int val, int p = MOD) {if ((a = (a + val)) >= p) a -= p;}
inline void submod(int& a, int val, int p = MOD) {if ((a = (a - val)) < 0) a += p;}
inline int mult(int a, int b, int p = MOD) {return (ll) a * b % p;}
inline int inv(int a, int p = MOD) {return fpow(a, p - 2, p);}
inline int sign(ld x) {return x < -EPS ? -1 : x > +EPS;}
inline int sign(ld x, ld y) {return sign(x - y);}
#define db(x) cerr << #x << " = " << (x) << " ";
#define endln cerr << "\n";
mt19937 mt(chrono::high_resolution_clock::now().time_since_epoch().count());
inline int myrand() {return abs((int) mt());}

void chemthan() {
    long long n, l, r, k;
    cin >> n >> l >> r >> k;
    long long d = r - l + 1;
    if (d <= 0) d += n;
    if (d == n) {
        long long res = -1;
        for (long long x = 1; x * x <= k; x++) {
            if (k % x == 0) {
                long long y = k / x;
                for (long long z : {x, y}) {
                    if (n <= z && z <= n + n) {
                        chkmax(res, z - n);
                    }
                }
            }
        }
        for (long long x = 1; x * x <= k + 1; x++) {
            if ((k + 1) % x == 0) {
                long long y = (k + 1) / x;
                for (long long z : {x, y}) {
                    if (n < z && z <= n + n) {
                        chkmax(res, z - n);
                    }
                }
            }
        }
        cout << res << "\n";
        return;
    }
    int lim = 1e6;
    if (n <= lim) {
        for (long long t = n; t >= 0; t--) {
            long long rr = k % (n + t);
            if (d + max(1LL, t - n + d) - 1 <= rr && rr <= d + min(d, t)) {
                cout << t << "\n";
                return;
            }
        }
        cout << -1 << "\n";
        return;
    }
    long long res = -1;
    FOR(i, 0, lim + 1) {
        long long lo = max(n, k / (i + 1) + 1) - n;
        long long hi = (i ? min(n + n, k / i) : n + n) - n;
        if (lo <= hi) {
            vector<long long> vals;
            vals.pb(lo), vals.pb(hi);
            if (lo <= d && d <= hi) {
                vals.pb(d);
            }
            if (lo <= n - d && n - d <= hi) {
                vals.pb(n - d);
            }
            sort(all(vals));
            FOR(j, 0, sz(vals) - 1) {
                long long u = vals[j] - 1;
                long long v = vals[j + 1];
                while (u < v) {
                    long long w = u + v + 1 >> 1;
                    if (d + max(1LL, w - n + d) - 1 <= k - (n + w) * i && k - (n + w) * i <= d + min(d, w)) {
                        u = w;
                    }
                    else {
                        v = w - 1;
                    }
                }
                long long w = u + v >> 1;
                if (w > vals[j] - 1) {
                    chkmax(res, w);
                }
            }
        }
    }
    cout << res << "\n";
}

int main(int argc, char* argv[]) {
    ios_base::sync_with_stdio(0), cin.tie(0);
    if (argc > 1) {
        assert(freopen(argv[1], "r", stdin));
    }
    if (argc > 2) {
        assert(freopen(argv[2], "wb", stdout));
    }
    chemthan();
    cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

const long long MAX_D = 1e6;

long long dist(long long a, long long b, long long n)
{
    if (a <= b)
    {
        return b - a + 1;
    }
    return n - (a - b + 1);
}

long long solve(long long n, long long k, long long l, long long r, bool last)
{
    long long b = dist(l, r, n);
    long long a = n - b;
    long long answer = -1;
    if (k <= 2 * b)
    {
        answer = k - b + a;
        if (k + 1 <= 2 * b)
        {
            answer++;
        }
    }

    for (long long c = 1; c < MAX_D; c++)
    {
        long long t = k % c;
        l = -1;
        r = k;
        while (r - l > 1)
        {
            long long m = (l + r) / 2;
            if (k - t - c * m <= 0)
            {
                r = m;
                continue;
            }
            if (t + c * m > 2 * b)
            {
                r = m;
                continue;
            }
            if (t + c * m < b)
            {
                l = m;
                continue;
            }
            long long sum = (k - t - c * m) / c;
            long long s = sum - t - c * m;
            if (s > 2 * a)
            {
                l = m;
            }
            else if (s < a)
            {
                r = m;
            }
            else
            {
                if (!last || t + c * m > b)
                {
                    answer = max(answer, sum - n);
                }

            //    cout << "ans == " << answer << ", c == " << c << ", t == " << t + c * m << ", s == " << s << ", m == " << m << "\n\n";
                r = m;
            }
        }
    }

    for (long long sum = n; sum < MAX_D; sum++)
    {
        long long t = k % sum;
        l = -1;
        r = t;
        while (r - l > 1)
        {
            long long m = (l + r) / 2;
            if (k - t - m * sum <= 0)
            {
                r = m;
                continue;
            }
            if (t + m * sum > 2 * b)
            {
                r = m;
                continue;
            }
            if (t + m * sum < b)
            {
                l = m;
                continue;
            }
            long long s = sum - t;
            if (s > 2 * a)
            {
                l = m;
            }
            else if (s < a)
            {
                r = m;
            }
            else
            {
                if (!last || t + m * sum > b)
                {
                    answer = max(answer, sum - n);
                    break;
                }
                l = m;
            }
        }
    }

    return answer;
}

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    long long n, l, r, k;
    cin >> n >> l >> r >> k;
    long long answer = max(solve(n, k, l, r, false), solve(n, k + 1, l, r, true));

    cout << answer;
    return 0;
}