//package CodeForces.Round516_div2;

import java.util.Scanner;

/**
 * @Author: tianchengjiang
 * @Date：2018/10/22
 */
public class problemF {
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while(scanner.hasNext()){
            long n = scanner.nextLong();
            long l = scanner.nextLong();
            long r = scanner.nextLong();
            long k = scanner.nextLong();
            long maxm = -1;
            if(r>=l){
                long rest = k - (r-l+1);
                if(rest<0){
                    maxm = -1;
                }else if(rest == 0){
                    maxm = n;
                }else if(rest > n){
                    for(int i=0;n*i<=rest;i++){
                        long right = rest-n*i;
                        long rangeX = r-l+1;
                        long rangeY = n-r+l-1;
                        if(rangeX > rangeY && rangeY!=0){
                            for(long j=0;j<=rangeY;j++){
                                long x = (right- i * j)/(i+1);
                                long x1 = (right+1 -i*j)/(i+1);
                                long left = x*(i+1) +i*j;
                                long left1 = x1*(i+1) +i*j;
                                if(left == right && x>=0 && x<= rangeX){
                                    if(x+j>maxm){
                                        maxm = i==0? n-r+l-1 + x+j : x+j;
                                    }
                                }else if(left1 == right+1 && x1>=0 && x1<=rangeX){
                                    if(x1+j > maxm){
                                        maxm = i==0 ? n-r+l-1 + x1+j :x1+j;
                                    }
                                }
                            }
                        }else{
                            for(long j=0;j<=rangeX;j++){
                                long y = right - (i+1)*j;
                                long y1 = right+1 - (i+1)*j;
                                if(i!=0) {
                                    y = (right- (i+1) * j)/(i);
                                    y1 = (right+1 -(i+1)*j)/i;
                                }
                                long left = j* (i+1) + i*y;
                                long left1 = j* (i+1) + i*y1;
                                if(left == right &&  y<= rangeY && y>=0){
                                    if(y+j>maxm){
                                        maxm = i==0 ? n-r+l-1 + y+j : y+j;
                                    }
                                }else if(left1 == right+1 && y1<=rangeY && y1>= 0){
                                    if(y1+j>maxm){
                                        maxm = i==0 ? n-r+1-1 +y1+j :y +j;
                                    }
                                }
                            }
                        }
                    }
                }
                System.out.println(maxm);
            }else{
                long rest = k + (l-r-1);
                if(rest - n <0){
                    maxm = -1;
                }else if(rest == n){
                    maxm = l-r;
                }else if(rest >= n){
                    for(int i=0;n*(i+1)<=rest;i++){
                        long right = rest-n*(i+1);
                        long rangeX = l-r-1;
                        long rangeY = n-l+r+1;
                        if(rangeX > rangeY && rangeY!=0){
                            for(long j=0;j<=rangeY;j++){
                                long x = (right- (i+1) * j);
                                long x1 = right+1 - (i+1)*j;
                                if(i!=0) {
                                    x = (right- (i+1) * j)/(i);
                                    x1 = (right+1 -(i+1)*j)/i;
                                }
                                long left =  x*i + (i+1)*j;
                                long left1 = x1*j + (i+1)*j;
                                if(left == right && x>=0 && x<= rangeX){
                                    if(x+j>maxm){
                                        maxm = i==0 ? x+j+l-r-1 : x+j;
                                    }
                                }else if(left1 == right+1 && x1>=0 &&x1<=rangeX){
                                    if(x1+j>maxm){
                                        maxm = i==0 ? x1+j+l-r-1 : x1+j;
                                    }
                                }
                            }
                        }else{
                            for(long j=0;j<=rangeX;j++){
                                long y = (right - (i)*j)/(i+1);
                                long y1 = (right + 1 -(i)*j)/(i+1);
                                long left = j * i + (i+1) * y ;
                                long left1 = j * i +(i+1) *y1;
                                if( left == right  &&  y<= rangeY && y>=0){
                                    if(y+j>maxm){
                                        maxm = i==0 ? y+j+l-r-1 : y+j;
                                    }
                                }else if( left1 == right+1 && y1<=rangeY && y1>=0){
                                    if(y1+j>maxm){
                                        maxm = i==0 ? y1+j+l-r-1 : y1+j;
                                    }
                                }
                            }
                        }
                    }
                }
                System.out.println(maxm);
            }
        }
    }

}


// package Incomplete;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;
import java.io.InputStreamReader;

public class Main {
    public static boolean checktriangle(int x1, int y1, int x2, int y2, int x3, int y3){
        double a = dist2(x1, y1, x2, y2);
		double b = dist2(x2, y2, x3, y3);
		double c = dist2(x1, y1, x3, y3);
		if (a <=  b+c || b<= a+c || c <= a+b)return false;
		if (a+b == c || b+c == a || a+c == b){
		    return true;
		}
		return false;
    }

    public static double dist2(int x1, int y1, int x2, int y2){
        return (double)((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
    }

	static final BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
	public static void main(String args[]) throws java.lang.Exception	{
		String s[] = br.readLine().split(" ");
		int x1 = Integer.parseInt(s[0]);int y1 = Integer.parseInt(s[1]);
		int x2 = Integer.parseInt(s[2]);int y2 = Integer.parseInt(s[3]);
		int x3 = Integer.parseInt(s[4]);int y3 = Integer.parseInt(s[5]);
		if (checktriangle(x1, y1, x2, y2, x3, y3))
		    System.out.println("RIGHT");
		else if (checktriangle(x1+1, y1, x2, y2, x3, y3) ||
		checktriangle(x1-1, y1, x2, y2, x3, y3) ||
		checktriangle(x1, y1+1, x2, y2, x3, y3) ||
		checktriangle(x1, y1-1, x2, y2, x3, y3) ||
		checktriangle(x1, y1, x2+1, y2, x3, y3) ||
		checktriangle(x1, y1, x2-1, y2, x3, y3) ||
		checktriangle(x1, y1, x2, y2+1, x3, y3) ||
		checktriangle(x1, y1, x2, y2 -1, x3, y3) ||
		checktriangle(x1, y1, x2, y2, x3+1, y3) ||
		checktriangle(x1, y1, x2, y2, x3-1, y3) ||
		checktriangle(x1, y1, x2, y2, x3, y3+1) ||
		checktriangle(x1, y1, x2, y2, x3, y3-1))
		    System.out.println("ALMOST");
        else System.out.println("NEITHER");
	}
}


import java.util.*;
import static java.lang.Math.*;
import java.io.*;

public class C {
	static void p(Object ...o) {System.out.println(Arrays.deepToString(o));};
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String S = in.next();
		System.out.println(solution(S));
		/*int N = 10;
		for (int i = 0; i < (1<<N); i++) {
			String S = "";
			for (int j = 0; j < N; j++) {
				if ((i&(1<<j)) != 0)
					S += "B";
				else
					S += "A";
			}
			System.out.println(S+" "+solution(S));
		}*/
	}
	static long solution(String S) {
		String A = make_swap(S);
		if (A.charAt(A.length()-1) == 'B' && A.charAt(0) == 'A')
			A = "S"+A.substring(1, A.length()-1);

		char[] C = A.toCharArray();
		int N = C.length;
		boolean[] V = new boolean[N];
		DP = new long[2][2][N+1];
		for (int i = 0; i < 2; i++)
			for(int j = 0; j < 2; j++)
				Arrays.fill(DP[i][j], -1);
		long ans = 1;
		for (int i = 0; i < N; i++) {
			if (V[i])
				continue;
			if (C[i] == 'S') {
				V[i] = true;
				int len = 1;
				while (len < N && C[(i+len)%N] == 'S') {
					V[(i+len)%N] = true;
					len++;
				}
				long ways = 0;
				if (len == N) {
					ways += solve(0, 0, N-1);
					ways += solve(1, 1, N-1);
				} else {
					char before = C[(i+N-1)%N];
					char after = C[(i+len)%N];
					ways += solve(before == 'A' ? 1 :0, after == 'B' ? 1 :0, len);
				}
				ans *= ways;
			}
		}
		return ans;
	}
	static long[][][] DP;
	private static long solve(int before, int after, int len) {
		if (DP[before][after][len] != -1)
			return DP[before][after][len];
		long ans = 0;
		if (len == 1) {
			if(before == 0 && after == 0)
				ans = 2;
			else
				ans = 1;
		} else {
			if (before == 0) {
				ans += solve(0, after, len-1);
			}
			ans += solve(1, after, len-1);
		}
		DP[before][after][len] = ans;
		return ans;
	}
	static String make_swap(String S) {
		String A = "";
		for (int i = 0; i < S.length(); i++) {
			if (i +1 < S.length() && S.charAt(i) == 'B' && S.charAt(i+1) == 'A') {
				A += "S";
				i++;
			} else {
				A += S.charAt(i);
			}
		}
		return A;
	}
}


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: contest
 * Date: 7/14/12
 * Time: 11:36 AM
 * To change this template use File | Settings | File Templates.
 */
public class problemC {
    final String prefix = "c";
    final String problem_input = prefix + ".in";
    final String problem_output = prefix + ".out";
    BufferedReader br;
    StringTokenizer st;
    PrintWriter out;
    String s;
    BigInteger dp[][];
    void load() throws IOException
    {
        s = nextToken();
    }
    int first;

    BigInteger f(int i, int m)
    {
        if (i == s.length())
        {
            if (m == first)
                return BigInteger.ONE;
            else return BigInteger.ZERO;
        }
        if (dp[i][m] != null) return dp[i][m];
        dp[i][m] = BigInteger.ZERO;
        if (s.charAt(i) == 'A')
        {
            if ((m & 1) == 0) // _A
            {
                dp[i][m] = dp[i][m].add(f(i + 1, ((m << 1) | 0) & 3));
            }
            else //_B
            {
                if ((m & 2) == 0)
                    for (int j = 0; j < 2; j++)
                        dp[i][m] = dp[i][m].add(f(i + 1, ((m << 1) | j) & 3));
            }
        }
        else if (s.charAt(i) == 'B')
        {
            if ((m & 1) == 1) // _B
            {                    //BB
                if ((m & 2) > 0) // B
                {
                    for (int j = 0; j < 2; j++)
                        dp[i][m] = dp[i][m].add(f(i + 1, ((m << 1) | j) & 3));
                }
            }
            else // _A
            {
                dp[i][m] = f(i + 1, ((m << 1) | 1) & 3);
            }
        }
        return dp[i][m];
    }
    void solve()
    {
        dp = new BigInteger[s.length() + 2][4];
        BigInteger res = BigInteger.ZERO;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < s.length() + 1; j++)
                dp[j][0] = dp[j][1] = dp[j][2] = dp[j][3] = null;
            first = i;
            res = res.add(f(0, i));
        }
        out.println(res);
    }
    void run()
    {
        try
        {
            br = new BufferedReader(new FileReader(problem_input));
            out = new PrintWriter(problem_output);
            load();
            solve();
            out.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            System.exit(42);
        }
    }
    public String nextToken() throws IOException {
        while (st == null || !st.hasMoreTokens())
        {
            st = new StringTokenizer(br.readLine());
        }
        return st.nextToken();
    }
    public int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    public long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    public double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
    public void readIntArray(int []a, int n) throws IOException
    {
        for (int i = 0; i < n; i++)
            a[i] = nextInt();
    }
    public static void main(String args[])
    {
        new problemC().run();
    }
}


import java.util.Scanner;

public class RoundHouse {

	public static void main(String[] args) {
		Scanner s=new Scanner(System.in);
		int n=s.nextInt();
		int a=s.nextInt();
		int b=s.nextInt();
		int k;
		if(b>=0){
			k=a+b;
		}
		else{
			k=a+Math.abs(b);
		}
		if(k>n){
			while(k>n){
				k=a+(k-n);
			}
		}
		System.out.println(k);
	}
}


import java.util.Scanner;

public class Apartment {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int n=in.nextInt();
		int k=in.nextInt();
		if(k!=0) {
			System.out.print((n==k)?0+" ":1+" ");
			int []a=new int[n+2];
			a[0]=2;
			a[n+1]=2;
			int iter=0;
			here:for(int i=2;iter<k;i+=3) {
				if(i>n) {
					for(int j=1;;j+=3) {
						if(j>n) {
							for(int m=3;;m+=3) {
								if(m>n)
									break here;
								else {
									a[m]=1;
									iter++;
									if(iter>=k)
										break here;
								}
							}
						}
						else {
							a[j]=1;
							iter++;
							if(iter>=k)
								break here;
						}
					}
				}
				else {
					a[i]=1;
					iter++;
				}

			}
			int ite=0;
			for(int i=1;i<n+1;i++) {
				if(a[i]==0&&(a[i-1]==1||a[i+1]==1))
					ite++;
			}
			System.out.print((n==k)?0:ite);
		}
		else
			System.out.print(0+" "+0);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;

public class C {

    public static void main(String[] args) {

        MyScanner in = new MyScanner();
        PrintWriter out = new PrintWriter(System.out);

        String f0 = "What are you doing at the end of the world? Are you busy? Will you save us?";
        String p1 = "What are you doing while sending \"";
        String p2 = "\"? Are you busy? Will you send \"";
        String p3 = "\"?";

        BigInteger[] len = new BigInteger[100_001];
        len[0] = new BigInteger(""+f0.length());

        for(int i=1;i<len.length;++i){
            len[i] = new BigInteger(""+(p1.length() +p2.length() + p3.length())).add(len[i-1].multiply(new BigInteger("2")));
        }

        int q = in.nextInt();
        for(int i=0;i<q;++i){
            int n = in.nextInt();
            long k = in.nextLong()-1;
            out.print(find(f0,p1,p2,p3,len, n, new BigInteger(""+k)));
        }

        out.close();
    }

    private static char find(String f0, String p1, String p2, String p3, BigInteger[] len, int index, BigInteger charIndex) {
        if(charIndex.compareTo(len[index])>0){
            return '.';
        }

        if(index==0){
            return f0.charAt(charIndex.intValue());
        }

        if(charIndex.compareTo(BigInteger.valueOf(p1.length()))<0){
            return p1.charAt(charIndex.intValue());
        }else if(charIndex.compareTo(BigInteger.valueOf(p1.length()).add(len[index-1]))<0){
            return find(f0,p1,p2,p3, len, index-1, charIndex.subtract(BigInteger.valueOf(p1.length())));
        }else if(charIndex.compareTo(len[index-1].add(BigInteger.valueOf(p1.length()  + p2.length())))<0){
            return p2.charAt((charIndex.subtract(len[index-1]).intValue() - p1.length()));
        }else if(charIndex.compareTo(len[index-1].multiply(BigInteger.valueOf(2)).add(BigInteger.valueOf(p1.length() + p2.length())))<0){
            return find(f0,p1,p2,p3, len, index-1, charIndex.subtract(len[index-1]).subtract(BigInteger.valueOf(p1.length() + p2.length())));
        }else {
            return p3.charAt(charIndex.subtract(len[index-1]).subtract(len[index-1]).subtract(BigInteger.valueOf(p1.length() + p2.length())).intValue());
        }
    }

    // -----------MyScanner class for faster input----------
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

    }
    // --------------------------------------------------------

}


import java.util.*;
import java.io.*;
import java.math.*;

public class B {
    public static StreamTokenizer in = new StreamTokenizer(System.in);
    public static boolean bg = true;

    public static void main(String[] args) throws Exception {
        in = null;
        Scanner scan = new Scanner(System.in);
        String[] l1 = scan.next().split(":");
        char[] ll1 = l1[0].toCharArray();
        char[] ll2 = l1[1].toCharArray();

        int[] v1 = new int[ll1.length];
        int[] v2 = new int[ll2.length];
        for (int i=0;i<ll1.length;i++){
            v1[i] = qq(ll1[i]);
        }
        for (int i=0;i<ll2.length;i++){
            v2[i] = qq(ll2[i]);
        }

        if (check(v1,v2)){
            pn(-1);
            ex();
        }

        HashSet<Integer> s1 = new HashSet();
        for (int i=1;;i++){
            if (ok(v1,i) ){
                int cur = parse(v1, i);
                if (cur<=23){
                    s1.add(i);
                }
                else {
                    break;
                }
            }
        }

        HashSet<Integer> s2 = new HashSet();
        for (int i=1;;i++){
            if (ok(v2,i) ){
                int cur = parse(v2, i);
                if (cur<=59){
                    s2.add(i);
                }
                else {
                    break;
                }
            }
        }

        //pn(s1);
        //pn(s2);

        s1.retainAll(s2);

        ArrayList<Integer> fin = new ArrayList();
        fin.addAll(s1);
        Collections.sort(fin);

        if (fin.size()==0){
            pn(0);
            ex();
        }

        for (int e: fin){
            p(e+" ");
        }
        pn("");

    }
    public static boolean check(int[] l1, int[] l2){
        ArrayList<Integer> f1 = new ArrayList();
        ArrayList<Integer> f2 = new ArrayList();
        for (int i=0;i<l1.length-1;i++){
            if (l1[i]!=0) return false;
        }
        for (int i=0;i<l2.length-1;i++){
            if (l2[i]!=0) return false;
        }
        if (l1[l1.length-1]<=23
                &&l2[l2.length-1]<=59
                ){
            return true;
        }
        return false;
    }
    public static int parse(int[] l1, int rdx){
        int fin = 0;
        for (int e: l1){
            fin *= rdx;
            fin += e;
        }
        return fin;
    }
    public static boolean ok(int[] l1, int rdx){
        for (int e: l1){
            if (rdx <=e) return false;
        }
        return true;
    }
    public static int qq(char c1){
        if (c1 - '0'>=0
                &&c1 - '0'<=9
                ){
            return c1 - '0';
        }
        else return c1 - 'A' + 10;
    }
    private static int ni() throws Exception {
        in.nextToken();
        return (int) in.nval;
    }

    private static long nl() throws Exception {
        in.nextToken();
        return (long) in.nval;
    }

    private static double nd() throws Exception {
        in.nextToken();
        return in.nval;
    }

    private static void pn(Object o1) {
        System.out.println(o1);
    }

    private static void p(Object o1) {
        System.out.print(o1);
    }

    private static void ex() {
        System.exit(0);
    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		while(n!=0) {
			int i = sc.nextInt();
			int sum = 0;
			sum = (i%10-1)*10;
			int j=1;
			while(i!=0) {
				sum+= j;
				i%=10;
				j++;
			}
			System.out.println(sum);
			n--;
		}
		sc.close();}

}


import java.io.*;
import java.util.*;

public class A764 {
    public static void main(String [] args) {
        InputStream inputReader = System.in;
        OutputStream outputReader = System.out;
        InputReader in = new InputReader(inputReader);
        PrintWriter out = new PrintWriter(outputReader);
        Algorithm solver = new Algorithm();
        solver.solve(in, out);
        out.close();
    }
}

class Algorithm {
    void solve(InputReader ir, PrintWriter pw) {
        double h = 0;
        double d = ir.nextInt();
        double L = ir.nextInt();
        double v1 = ir.nextInt();
        double v2 = ir.nextInt();
        double count = 0;

        while (L - h > d) {
            if ((L - v2) - (h + v1) > d) {
                L = L - v2;
                h = h + v1;
                count++;
            } else if ((L - v2) - (h + v1) == d) {
                count++;
                break;
            } else {
                count = count + (L - h - d) / (L - h);
                break;
            }
        }

        pw.print(count);

    }

    private static void Qsort(int[] array, int low, int high) {

        int i = low;
        int j = high;
        int x = array[low + (high - low) / 2];

        do {
            while (array[i] < x) ++i;
            while (array[j] > x) --j;
            if (i <= j) {
                int tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
                i++;
                j--;
            }
        } while (i <= j);

        if (low < j) Qsort(array, low, j);
        if (i < high) Qsort(array, i, high);

    }
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

    InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream), 32768);
        tokenizer = null;
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
    long nextLong() {
        return Long.parseLong(next());
    }

}


import java.io.*;
import java.util.*;

public class Task630C {

    public static void main(String... args) throws NumberFormatException,
            IOException {
        Solution.main(System.in, System.out);
    }

    static class Strings {
        static boolean isPalindrome(String inp) {
            for (int i = 0; i < inp.length(); i++) {
                if (inp.charAt(i) != inp.charAt(inp.length() - 1 - i)) {
                    return false;
                }
            }
            return true;
        }
    }

    static class Scanner implements AutoCloseable {

        private final BufferedReader br;
        private String[] cache;
        private int cacheIndex;

        Scanner(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
            cache = new String[0];
            cacheIndex = 0;
        }

        int nextInt() throws IOException {
            if (cacheIndex >= cache.length) {
                cache = br.readLine().split(" ");
                cacheIndex = 0;
            }
            return Integer.parseInt(cache[cacheIndex++]);
        }

        long nextLong() throws IOException {
            if (cacheIndex >= cache.length) {
                cache = br.readLine().split(" ");
                cacheIndex = 0;
            }
            return Long.parseLong(cache[cacheIndex++]);
        }

        String next() throws IOException {
            if (cacheIndex >= cache.length) {
                cache = br.readLine().split(" ");
                cacheIndex = 0;
            }
            return cache[cacheIndex++];
        }

        public void close() throws IOException {
            br.close();
        }

    }

    static class Solution {

        public static int GCD(int a, int b) {
            return b == 0 ? a : GCD(b, a % b);
        }

        public static void main(InputStream is, OutputStream os)
                throws NumberFormatException, IOException {

            try (PrintWriter pw = new PrintWriter(os)) {
                try (Scanner sc = new Scanner(is)) {

                    double l = sc.nextInt();
                    double d = sc.nextInt();
                    double v1 = sc.nextInt();
                    double v2 = sc.nextInt();

                    pw.println((l - d) / (v1 + v2));

                }
            }
        }
    }
}


import java.util.*;
import java.math.*;
public class Main{
        private static int max=200*1000+5;
        public static void main(String args[]){
                Scanner sc=new Scanner(System.in);
                int n=sc.nextInt();
                int k=sc.nextInt();
                int a[]=new int[n];
                for(int i=0;i<n;i++){
                        a[i]=sc.nextInt();
                }
                List<Integer> [] vals=new ArrayList<Integer>[max];
                for(int i=0;i<max;i++){
                        vals[i]=new ArrayList<Integer>();
                }
                for(int i:a){
                        int y=i;
                        int cur=0;
                        while(y>0){

                                vals[y].add(cur);
                                y=y/2;
                                cur++;
                        }
                }
                int res=Integer.MAX_VALUE;
                for(List<Integer> l:vals){
                        if(l.size()>=k){
                                Collections.sort(l);
                                int t=0;
                                for(int i=0;i<k;i++){
                                        t+=l.add(i);
                                }
                                 res=Math.min(t,res);
                        }

                }
                System.out.println(res);
        }
}


import java.util.*;

public class codeforces {

    static class pair
    {
        int element;
        int cost;
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        int[] arr = new int[n];
        int max = 0;
        for(int i=0;i<n;i++) {
            arr[i] = sc.nextInt();
            max = Math.max(max,arr[i]);
        }
        int[][] matrix = new int[max+1][max+1];

        for(int i=0;i<n;i++)
        {
            int temp = arr[i];
            int count = 0;

            while(true)
            {
                matrix[temp][count] = matrix[temp][count] + 1;
                if(temp == 0)
                    break;
                temp = temp / 2;
                count++;
            }
        }

        //System.out.println(Arrays.deepToString(matrix));
        long ans = Long.MAX_VALUE;
        for(int i=0;i<=max;i++)
        {
            long temp = 0;
            long element = 0;
            for(int j=0;j<=max;j++)
            {
                element = element + matrix[i][j];
                if(element<k) {
                    temp += matrix[i][j] * j;
                }
                else if(element==k)
                {
                    temp += matrix[i][j] * j;
                    break;
                }
                else if(element>k)
                {
                    temp += ( (k- (element - matrix[i][j]) ) * j);
                    break;
                }
            }
            //System.out.println(i+" cost::" + temp+ " element:"+element);
            if(element>=k)
                ans = Math.min(ans,temp);
        }
        System.out.println(ans);

    }

}


import java.io.*;
import java.util.*;

public class BeaverGame implements Runnable {

		int split = 0;
		long val = 0;
		long count = 0;
		boolean canSplit(long n, int k, int m){
			for(int i=k;i<=m/2;i++){
				if(m%i==0){
					split = i;
					count += val;
					val = m/i * n;
					return true;
				}
			}
			return false;
		}

        void solve() throws IOException {
        	long n = nextLong();
        	int m = nextInt();
        	int k = nextInt();
        	val = n;

        	while(canSplit(n,k,m)){
        		m = split;
        		n = val;
        	}
        	if(count%2==0){
        		writer.println("Marsel");
        	}
        	else
        		writer.println("Timur");
         }

        BufferedReader reader;
        StringTokenizer tokenizer;
        PrintWriter writer;

        public void run() {
            try {
                reader = new BufferedReader(new InputStreamReader(System.in));
                writer = new PrintWriter(System.out);
                //reader = new BufferedReader(new FileReader("input.txt"));
                //writer = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
                tokenizer = null;
                solve();
                reader.close();
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        int nextInt() throws IOException {
            return Integer.parseInt(nextToken());
        }

        long nextLong() throws IOException {
            return Long.parseLong(nextToken());
        }

        double nextDouble() throws IOException {
            return Double.parseDouble(nextToken());
        }

        String nextToken() throws IOException {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
            return tokenizer.nextToken();
        }

        public static void main(String[] args) {
                new BeaverGame().run();
        }

}


import java.util.Scanner;

public class Polykarp {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		int k = in.nextInt();
		int a = in.nextInt() - 1;
		int b = in.nextInt() - 1;

		int ap = a/(m*k);
		int ae = (a%(m*k)) / k;

		int bp = b/(m*k);
		int be = (b%(m*k)) / k;

		int t = 0;

		if (ap == bp) {
			if (ae != be) {
				t = min(abs(ae - be)*5, 10 + abs(ae - be));
			}
		}
		else {
			t += min(ae*5, 10 + ae);
			t += min(mod(ap - bp, n), mod(bp - ap, n)) * 15;
			t += min(be*5, 10*be + 1);
		}

		System.out.print(t);
		in.close();
	}

	public static int min(int a, int b) {
		if (a < b) {
			return a;
		}
		else {
			return b;
		}
	}

	public static int abs(int a) {
		if (a >=0) {
			return a;
		}
		else {
			return -a;
		}
	}

	public static int mod(int a, int n) {
		while (a < 0) {
			a += n;
		}
		return a%n;
	}
}


import java.io.*;
import java.util.*;

public class Main {

	public static void main(String[] args) throws Exception {
		long time = System.nanoTime();

		long x = nextl();
		long y = nextl();
		long m = nextl();

		if (x >= m || y >= m) out.println(0);
		else {
			if (x <= 0 && y <= 0) out.println(-1);
			else {
				int c = 0;
				if (x < 0) {
					c += (y - x)/y;
					x += c*y;
				} else if (y < 0) {
					c += (x - y)/x;
					y += c * x;
				}

				while (x < m && y < m) {
					if (x > y) y += x;
					else x += y;
					c++;
				}
				out.println(c);
			}
		}

//		System.out.println((System.nanoTime() - time)* 1e-9);
		out.close();
	}
	static PrintWriter out = new PrintWriter(System.out);

	static BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	static StringTokenizer in = new StringTokenizer("");

	static String nextToken() throws Exception {
		if (!in.hasMoreTokens()) in = new StringTokenizer(bufferedreader.readLine());
		return in.nextToken();
	}

	static int next()  throws Exception {return Integer.parseInt(nextToken());};
	static int[] next(int n) throws Exception {
		int[] x = new int[n];
		for (int i = 0; i < n; i++) x[i] = next();
		return x;
	}
	static int[][] next(int n, int m) throws Exception {
		int[][] x = new int[n][];
		for (int i = 0; i < n; i++) x[i] = next(m);
		return x;
	}

	static long nextl() throws Exception {return Long.parseLong(nextToken());};
	static long[] nextl(int n) throws Exception {
		long[] x = new long[n];
		for (int i = 0; i < n; i++) x[i] = nextl();
		return x;
	}
	static long[][] nextl(int n, int m) throws Exception {
		long[][] x = new long[n][];
		for (int i = 0; i < n; i++) x[i] = nextl(m);
		return x;
	}

	static double nextd() throws Exception {return Double.parseDouble(nextToken());};
	static double[] nextd(int n) throws Exception {
		double[] x = new double[n];
		for (int i = 0; i < n; i++) x[i] = nextd();
		return x;
	}
	static double[][] nextd(int n, int m) throws Exception {
		double[][] x = new double[n][];
		for (int i = 0; i < n; i++) x[i] = nextd(m);
		return x;
	}

	static String nextline() throws Exception {
		in = new StringTokenizer("");
		return bufferedreader.readLine();
	}

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            DSingerHouse solver = new DSingerHouse();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class DSingerHouse {
        Debug debug = new Debug(true);

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int m = n + 2;
            int[][] dp = new int[n + 1][m + 1];

            Modular mod = new Modular(1e9 + 7);
            Combination comb = new Combination(10000, mod);

            dp[0][0] = 1;
            for (int i = 1; i <= n; i++) {
                for (int j = 0; j <= m; j++) {
                    if (dp[i - 1][j] == 0) {
                        continue;
                    }
                    for (int k = 0; k <= m; k++) {
                        if (dp[i - 1][k] == 0) {
                            continue;
                        }
                        int way = mod.mul(dp[i - 1][j], dp[i - 1][k]);
                        if (j + k <= m) {
                            //not appear
                            int next = j + k;
                            dp[i][next] = mod.plus(dp[i][next], way);
                        }
                        if (j + k - 1 <= m && j + k - 1 >= 0) {
                            //appear, and concatenate
                            int next = j + k - 1;
                            int local = mod.mul(way, (j + k) * (j + k - 1));
                            dp[i][next] = mod.plus(dp[i][next], local);
                        }
//                    if (j + k - 1 <= m && j >= 1) {
//                        //appear, and concatenate left side
//                        int next = j - 1 + k;
//                        int local = mod.mul(way, j);
//                        local = mod.mul(local, j);
//                        dp[i][next] = mod.plus(dp[i][next], local);
//                    }
//                    if (j + k - 1 <= m && k >= 1) {
//                        //appear, and concatenate right side
//                        int next = j - 1 + k;
//                        int local = mod.mul(way, k);
//                        local = mod.mul(local, k);
//                        dp[i][next] = mod.plus(dp[i][next], local);
//                    }
                        if (j + k <= m) {
                            //appear, but only appear on one side
                            int next = j + k;
                            int local = mod.mul(way, 2 * (j + k));
                            dp[i][next] = mod.plus(dp[i][next], local);
                        }
                        if (j + k + 1 <= m) {
                            //appear, with new in/out
                            int next = j + k + 1;
                            dp[i][next] = mod.plus(dp[i][next], way);
                        }
                    }
                }
                dp[i][0] = 1;
            }

            debug.debug("dp", dp);
            int ans = dp[n][1];
            out.println(ans);
        }

    }

    static class Debug {
        private boolean offline;
        private PrintStream out = System.err;
        static int[] empty = new int[0];

        public Debug(boolean enable) {
            offline = enable && System.getSecurityManager() == null;
        }

        public Debug debug(String name, Object x) {
            return debug(name, x, empty);
        }

        public Debug debug(String name, Object x, int... indexes) {
            if (offline) {
                if (x == null || !x.getClass().isArray()) {
                    out.append(name);
                    for (int i : indexes) {
                        out.printf("[%d]", i);
                    }
                    out.append("=").append("" + x);
                    out.println();
                } else {
                    indexes = Arrays.copyOf(indexes, indexes.length + 1);
                    if (x instanceof byte[]) {
                        byte[] arr = (byte[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof short[]) {
                        short[] arr = (short[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof boolean[]) {
                        boolean[] arr = (boolean[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof char[]) {
                        char[] arr = (char[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof int[]) {
                        int[] arr = (int[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof float[]) {
                        float[] arr = (float[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof double[]) {
                        double[] arr = (double[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof long[]) {
                        long[] arr = (long[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else {
                        Object[] arr = (Object[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    }
                }
            }
            return this;
        }

    }

    static interface IntCombination {
    }

    static class Modular {
        int m;

        public int getMod() {
            return m;
        }

        public Modular(int m) {
            this.m = m;
        }

        public Modular(long m) {
            this.m = (int) m;
            if (this.m != m) {
                throw new IllegalArgumentException();
            }
        }

        public Modular(double m) {
            this.m = (int) m;
            if (this.m != m) {
                throw new IllegalArgumentException();
            }
        }

        public int valueOf(int x) {
            x %= m;
            if (x < 0) {
                x += m;
            }
            return x;
        }

        public int valueOf(long x) {
            x %= m;
            if (x < 0) {
                x += m;
            }
            return (int) x;
        }

        public int mul(int x, int y) {
            return valueOf((long) x * y);
        }

        public int plus(int x, int y) {
            return valueOf(x + y);
        }

        public String toString() {
            return "mod " + m;
        }

    }

    static class Factorial {
        int[] fact;
        int[] inv;
        Modular modular;

        public Modular getModular() {
            return modular;
        }

        public Factorial(int[] fact, int[] inv, InverseNumber in, int limit, Modular modular) {
            this.modular = modular;
            this.fact = fact;
            this.inv = inv;
            fact[0] = inv[0] = 1;
            for (int i = 1; i <= limit; i++) {
                fact[i] = modular.mul(fact[i - 1], i);
                inv[i] = modular.mul(inv[i - 1], in.inv[i]);
            }
        }

        public Factorial(int limit, Modular modular) {
            this(new int[limit + 1], new int[limit + 1], new InverseNumber(limit, modular), limit, modular);
        }

    }

    static class Combination implements IntCombination {
        final Factorial factorial;
        final Modular modular;

        public Combination(Factorial factorial) {
            this.factorial = factorial;
            this.modular = factorial.getModular();
        }

        public Combination(int limit, Modular modular) {
            this(new Factorial(limit, modular));
        }

    }

    static class InverseNumber {
        int[] inv;

        public InverseNumber(int[] inv, int limit, Modular modular) {
            this.inv = inv;
            inv[1] = 1;
            int p = modular.getMod();
            for (int i = 2; i <= limit; i++) {
                int k = p / i;
                int r = p % i;
                inv[i] = modular.mul(-k, inv[r]);
            }
        }

        public InverseNumber(int limit, Modular modular) {
            this(new int[limit + 1], limit, modular);
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(int c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }
}


import java.util.*;
import java.io.*;

public class codeforces
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);

		int n = in.nextInt();
		int x = in.nextInt();
		int y = in.nextInt();

		if((x==n/2 && y==n/2) || (x==n/2 || y==n/2+1) || (x==n/2+1 && y==n/2) || (x==n/2+1 && y==n/2+1))
			System.out.println("NO");
		else
			System.out.println("YES");
	}

}


/**
 * Created by IntelliJ IDEA.
 * User: shakhov
 * Date: 15.06.2011
 * Time: 15:22:46
 * To change this template use File | Settings | File Templates.
 */

//6
//86 402 133 524 405 610   6 4 1

import java.io.*;
import java.util.*;

public class CodeForces {
	double eps = 0.00001;

	public void solve() throws IOException {
		int n=nextInt();
		int x=nextInt();
		int y=nextInt();
		String res="YES";
		if(x==n/2 || x==n/2+1 || y==n/2 || y==n/2+1)
		{
			res="NO";
		}

		out.print(res);

	}

	private BufferedReader reader;
	private StringTokenizer tokenizer;
	private String separator;
	public PrintWriter out;

	public static void main(String[] args) throws IOException {
		// new CodeForces().run(new FileReader("input.txt"), new
		// FileWriter("output.txt"));
		new CodeForces().run(new InputStreamReader(System.in), new OutputStreamWriter(System.out));
	}

	public void run(Reader reader, Writer writer) {
		try {
			this.reader = new BufferedReader(reader);
			out = new PrintWriter(writer);
			tokenizer = new StringTokenizer("");
			separator = System.getProperty("line.separator");
			separator = Character.toString(separator.charAt(separator.length() - 1));
			long t1 = System.currentTimeMillis();
			solve();
			out.flush();
			reader.close();
			writer.close();
			long t2 = System.currentTimeMillis();
			System.err.println("Time = " + (t2 - t1));
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}

}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int e = sc.nextInt();
		int[] arr = new int[n+1];
		for(int i = 1;i<=n;i++) {
			arr[i] = arr[i-1]+i;
		}
		for(int i = 1;i<=n;i++) {
			if(arr[i]-(n-i)==e) {
				System.out.println(n-i);
				break;
			}
		}
		sc.close();
	}
}


import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);

		int n = in.nextInt();
		int k = in.nextInt();
		int[] a = new int[n];

		for(int i = 0; i < n; i++)
			a[i] = i + 1;

		int tmp = 0;
		int sum = 0;
		for(int i = 0; i < n; i++)
		{
			sum += a[i];
		}

		for(int i = n - 1; sum > k; i--)
		{
			tmp++;
			sum = sum - a[i] - 1;
		}

		out.println(tmp);

		out.close();
	}

	static class InputReader
	{
		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream)
		{
			reader = new BufferedReader(new InputStreamReader(stream), 32768);
			tokenizer = null;
		}

		public String next()
		{
			while(tokenizer == null || !tokenizer.hasMoreTokens())
			{
				try
				{
					tokenizer = new StringTokenizer(reader.readLine());
				}
				catch(IOException e)
				{
					throw new RuntimeException(e);
				}
			}

			return tokenizer.nextToken();
		}

		public int nextInt()
		{
			return Integer.parseInt(next());
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        Reader.init(System.in);
        int n = Reader.nextInt();
        int k = Reader.nextInt();

        int[] arr= new int[k];

        /*for (int i=0; i<n; i++){
            int val = Reader.nextInt();
            arr[val-1] = arr[val-1]+1;
        }
        int num_sets = n/2;
        if(n%2!=0){
            num_sets++;
        }
        int ans = 0;
        Arrays.sort(arr);
        for (int i=k-1; i>=0; i++){
            int num = arr[i];
            int sub = num/2;
            if (num%2==1){
                sub=sub+1;
            }
            if (num_sets-sub>=0){
                num_sets=num_sets-sub;
                ans=ans+num;
            }

        }*/
        int i= 0;
        long ate=0;
        long prev=0;
        long curr = 0;
        while(i<n){
            if (curr<=k){
                curr=curr+prev+1;
                prev=prev+1;
                i++;
            }
            else{
                ate=ate+1;
                curr=curr-1;
                i++;
            }
        }

        System.out.println(ate);
    }
}

/** Class for buffered reading int and double values */
class Reader {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */
    static void init(InputStream input) {
        reader = new BufferedReader(
                new InputStreamReader(input) );
        tokenizer = new StringTokenizer("");
    }

    /** get next word */
    static String next() throws IOException {
        while ( ! tokenizer.hasMoreTokens() ) {
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(
                    reader.readLine() );
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt( next() );
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble( next() );
    }
}


import java.util.Scanner;

/**
 *
 * @author hriti
 */
public class twoRoundTable {

    public static void main(String[] args)

    {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextInt();
        long output = fact(n)/(fact(n/2)*fact(n - n/2))/2*fact(n/2 - 1)*fact(n/2 - 1);
        System.out.println(output);
        sc.close();
    }

    static int fact(long n)
    {
        if(n <= 1)
        {
            return 1;
        }
        else
        return n*fact(n - 1);
    }
}


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);
        long n=sc.nextLong(),m=sc.nextLong(),a=sc.nextLong(),b=sc.nextLong(),sp=0,ss=0,i=m;
        if(n%m==0){System.out.println("0");}
        else if(n>m){ss=(n-m)*b;while(n>m){m+=i;}sp=(m-n)*a;if(sp<=ss){System.out.println(sp);}else{System.out.println(ss);}}
        else if(n<m){sp=(m-n)*a;ss=n*b;if(sp<=ss){System.out.println(sp);}else{System.out.println(ss);}}
    }
}


import java.util.*;
public class A
{
    public static long gcd(long a,long b)
    {
        if(b==0)
        return a;
        else
        return gcd(b,a%b);
    }
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        long a=sc.nextLong();
        long b=sc.nextLong();
        long x=sc.nextLong();
        long y=sc.nextLong();
        long w=gcd(x,y);
        x=x/w;
        y=y/w;
        long p=x;
        long q=y;
        long count=0;
        while(x<=a&&y<=b)
        {
            count++;
            x=x+p;
            y=y+q;
        }
        System.out.println(count);
    }
}


package skyglow1;

import java.util.Scanner;

public class Class1 {
	public static void main(String[]	args) {
		Scanner input=new Scanner(System.in);
		String s=input.next();
		boolean YES=true;
		for(int i=0;i<s.length()-1;i++) {
			if(s.charAt(i)!='a'&&
					s.charAt(i)!='e'&&
					s.charAt(i)!='o'&&
					s.charAt(i)!='u'&&
					s.charAt(i)!='i'&&
					s.charAt(i)!='n') {
				if(s.charAt(i+1)!='a'&&
						s.charAt(i+1)!='o'&&
						s.charAt(i+1)!='u'&&
						s.charAt(i+1)!='e'&&
						s.charAt(i+1)!='i') {
					YES=false;
					System.out.println(s.charAt(i));
					}
			}

		}
		if(s.charAt(s.length()-1)!='a'&&
				s.charAt(s.length()-1)!='u'&&
				s.charAt(s.length()-1)!='i'&&
				s.charAt(s.length()-1)!='e'&&
				s.charAt(s.length()-1)!='o'&&
				s.charAt(s.length()-1)!='n') {
			YES=false;
			System.out.println("WTF!");
			}
		if(YES)
			System.out.println("YES");
		else
			System.out.println("NO");

	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Scanner;

public class _172B {
	public static void main(String[] args) throws Exception {
		int t = sc.nextInt();
		while (t-- > 0)
			solve();
	}

	// **SOLUTION**
	public static void solve() throws Exception {
		int a = sc.nextInt();
		int b = sc.nextInt();
		int m = sc.nextInt();
		int r = sc.nextInt();

		int p = 0;
		HashMap<Integer, Integer> hm = new HashMap<>();
		hm.put(r, p);

		while (true) {
			p++;
			r = (a * r + b) % m;
			if (hm.containsKey(r)) {
				System.out.println(p - hm.get(r));
				return;
			} else {
				hm.put(r, p);
			}
		}
	}

	public static InputStreamReader r = new InputStreamReader(System.in);

	public static BufferedReader br = new BufferedReader(r);

	public static Scanner sc = new Scanner(System.in);
}


import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Árysson Cavalcanti
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskB {

    int[] p, e;
    IntPair[] arr;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n=in.readInt(), k=in.readInt(), x=0;
        p=new int[n];
        e=new int[n];
        IOUtils.readIntArrays(in, p, e);
        arr=new IntPair[n];
        for (int i=0; i<n; i++) arr[i]=new IntPair(e[i], i);
        Arrays.sort(arr);
        /*for (int i=0; i<n; i++)
                System.out.println(arr[i]);*/
        long total=ArrayUtils.sumArray(e);
        for (int i: p) if (i>n) x++;
        if (x+1>k) {
            out.printLine(-1);
            return;
        }
        out.printLine(MiscUtils.binarySearch(0, total, new Function<Long, Boolean>() {
            public Boolean value (Long amount) {
                //out.print(amount, "");
                long sum=0;
                int points=0, defeated=0;
                for (int i=0; i<n; i++) if (amount>=sum+arr[i].first) {
                    sum+=arr[i].first;
                    points++;
                }
                return n-Math.max(defeated(amount, points, n), defeated(amount, points-1, n))+1<=k;
            }
        }));
    }

    int defeated(long amount, int points, int n) {
                //out.print(amount, "");
                boolean[] vis=new boolean[n];
                int defeated=0;
                for (int i=0; i<points; i++){
                    amount-=arr[i].first;
                    vis[arr[i].second]=true;
                }
                List<IntPair> canWin=new ArrayList<>(), willLose=new ArrayList<>();
                //out.print(points, "");
                for (int i=0; i<n; i++) {
                    if (vis[i] && p[i]<points-1) willLose.add(new IntPair(e[i], i));
                    if (!vis[i] && (p[i]==points-1 || p[i]==points)) canWin.add(new IntPair(e[i], i));
                }
                Collections.sort(canWin);
                Collections.sort(willLose);
                Collections.reverse(willLose);
                //out.print(canWin, "\n");
                //out.print(willLose, "\n");
                int i=0;
                for (IntPair pair: willLose) if (i<canWin.size()) {
                    int x=canWin.get(i).second, y=pair.second;
                    if (amount+e[y]-e[x]>=0) {
                        amount+=e[y]-e[x];
                        vis[x]=true;
                        i++;
                    }
                }
                for (int j=0; j<n; j++) if (p[j]<points-1 || (vis[j] && p[j]<=points)) defeated++;
                return defeated;
            }
}

class IntPair implements Comparable<IntPair> {
    public final int first, second;

    public IntPair(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public String toString() {
        return "(" + first + "," + second + ")";
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        IntPair intPair = (IntPair) o;

        return first == intPair.first && second == intPair.second;

    }

    public int hashCode() {
        int result = first;
        result = 31 * result + second;
        return result;
    }

    public int compareTo(IntPair o) {
        if (first < o.first)
            return -1;
        if (first > o.first)
            return 1;
        if (second < o.second)
            return -1;
        if (second > o.second)
            return 1;
        return 0;
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public void print(Object...objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void close() {
        writer.close();
    }

    public void printLine(long i) {
        writer.println(i);
    }

    public void printLine(int i) {
        writer.println(i);
    }
}

class IOUtils {

    public static void readIntArrays(InputReader in, int[]... arrays) {
        for (int i = 0; i < arrays[0].length; i++) {
            for (int j = 0; j < arrays.length; j++)
                arrays[j][i] = in.readInt();
        }
    }

}

class ArrayUtils {

    public static long sumArray(int[] array) {
        long result = 0;
        for (int element : array)
            result += element;
        return result;
    }

}

class MiscUtils {

    public static long binarySearch(long from, long to, Function<Long, Boolean> function) {
        while (from < to) {
            long argument = from + (to - from) / 2;
            if (function.value(argument))
                to = argument;
            else
                from = argument + 1;
        }
        return from;
    }

}

interface Function<A, V> {
    public abstract V value(A argument);
}