import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Anon{
    static class Reader
    {
        private BufferedReader br;
        private StringTokenizer stkz;
        public Reader(InputStream obj)
        {
            br = new BufferedReader(new InputStreamReader(obj));
            stkz = null;
        }
        public String next()
        {
            while (stkz == null || !stkz.hasMoreElements())
            {
                try
                {
                    stkz = new StringTokenizer(br.readLine());
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return stkz.nextToken();
        }
        public long[] nextLongArr(int n)
        {
            long[] arr = new long[n];
            for(int i=0; i<n; i++){
                arr[i] = nextLong();
            }
            return arr;
        }
        public int[] nextIntArr(int n)
        {
            int[] arr = new int[n];
            for(int i=0; i<n; i++){
                arr[i] = nextInt();
            }
            return arr;
        }
        public Integer[] nextIntegerArray(int n)
        {
            Integer[] arr = new Integer[n];
            for(int i=0; i<n; i++){
                arr[i] = nextInt();
            }
            return arr;
        }
        public Long[] nextLongArray(int n)
        {
            Long[] arr = new Long[n];
            for(int i=0; i<n; i++){
                arr[i] = nextLong();
            }
            return arr;
        }
        public int nextInt()
        {
            return Integer.parseInt(next());
        }
        public long nextLong()
        {
            return Long.parseLong(next());
        }
        public double nextDouble()
        {
            return Double.parseDouble(next());
        }
        public String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static void main(String[] args) throws Exception{
        Reader in = new Reader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        String s1 = in.next(), s2 = in.next();
        String global = ""+s1.charAt(0)+s2.charAt(0);
        for (int i=0; i<s1.length(); i++) if (new String(""+s1.substring(0, i+1)+s2.charAt(0)).compareTo(global) < 0) global = new String(""+s1.substring(0, i+1)+s2.charAt(0));
        out.printf("%s\n", global);
        out.close();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;

/**
 * Created by Kamil Khadiev on 11.08.2015.
 */
public class khadiev_8V_c {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        init(in);
        in.close();
        solve();
        PrintWriter out = new PrintWriter(System.out);
        print(out);
        out.close();

    }
    public static int n,m;
    public static int[] a,b;
    public static long ans;
    public static int INF = Integer.MAX_VALUE/2;
static String s;
    private static void init(BufferedReader in) throws IOException {
        StringTokenizer st = new StringTokenizer(in.readLine().trim());
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());

    }

    private static void solve() {
        ans = 0;
        int x1 = 0;
        int x2 = 0;
        x1 = (n/2*6-2);
        if (n %2 == 1)x1+=4;
        x2 = (m*6-3);
        int xx1 = n%2;
        int y1 = (n-1)/2;
        int y2 = m-1;
        while (y1>0&& y2>0){
            if(x1>x2){
                if (xx1 ==0){
                    x1-=2;
                    xx1 = 1;
                }
                else{
                    x1 -=4;
                    y1--;
                    xx1 = 0;
                }
                if (y1 ==0){x1+=2;}
                y1--;
                y2--;
            }
            else{
                y2-=2;
                y1--;
                x2-=6;
                if (y2==-1) x2+=3;
            }
        }
        while (y1>0){
            if (xx1 ==0){
                x1-=2;
                xx1 = 1;
            }
            else{
                x1 -=4;
                y1--;
                xx1 = 0;
            }
            y1--;
        }
        if (y1==-1) x1+=2;
        if (y2>0){
            x2 -= 6*(y2/2);
            if (y2%2==1) x2-=3;
        }
        ans = Math.max(x2,x1);

    }

    private static void print(PrintWriter out) throws IOException {
        out.print(ans);
    }
}


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

public class j7 implements Runnable {

	public void run(){

		InputReader in =  new InputReader(System.in);
		PrintWriter w = new PrintWriter(System.out);

		long[] aa=new long[15];
		for(int i=1;i<=14;i++)
			aa[i]=in.nextLong();

		long max=0;

		for(int i=1;i<=14;i++)
		{

				long[] a=new long[15];
				for(int j=1;j<=14;j++)
					a[j]=aa[j];

				long st=a[i];
				a[i]=0;
				long m=st/14;

					for(int l=1;l<=14;l++)
						a[l]=a[l]+m;

				long ex=st%14;
				int k=i+1;

				if(k>14)
					k=k%14;

				for(int j=0;j<ex;j++)
				{

					a[k]++;
					k=k+1;
					if(k>14)
						k=k%14;

				}

				long count=0;
				for(int j=1;j<=14;j++)
				{

					if(a[j]%2==0 && a[j]>0)
						count+=a[j];
				}
				max=Math.max(max, count);
		}

		w.println(max);
		w.close();
	}

	static 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 String nextLine()
		{
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
		}
		public int nextInt()
		{
			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 long nextLong()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = read();
			}
			long 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 double nextDouble()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = read();
			}
			double res = 0;
			while (!isSpaceChar(c) && c != '.')
			{
				if (c == 'e' || c == 'E')
					return res * Math.pow(10, nextInt());
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			}
			if (c == '.')
			{
				c = read();
				double m = 1;
				while (!isSpaceChar(c))
				{
					if (c == 'e' || c == 'E')
						return res * Math.pow(10, nextInt());
					if (c < '0' || c > '9')
						throw new InputMismatchException();
					m /= 10;
					res += (c - '0') * m;
					c = read();
				}
			}
			return res * sgn;
		}

		public String readString()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = read();
			}
			while (!isSpaceChar(c));

			return res.toString();
		}

		public boolean isSpaceChar(int c)
		{
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public String next()
		{
			return readString();
		}

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

	public static void main(String args[]) throws Exception
	{
		new Thread(null, new j7(),"j7",1<<26).start();
	}
 }


import java.util.Scanner;

public class TaskB {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String x = in.nextLine();
        String result = computeMaxDigitSumNumber(x);
        System.out.println(result);
    }

    static String computeMaxDigitSumNumber(String x) {
        int len = x.length();
        if (len == 1) {
            return x;
        }
        int firstDigit = Character.getNumericValue(x.charAt(0));
        int secondDigit = Character.getNumericValue(x.charAt(1));
        String nines = repeatChar('9', len - 2);
        String xPostfix = x.substring(2);
        boolean endToNines = xPostfix.equals(nines);
        if (secondDigit < 8 || secondDigit == 8 && !endToNines) {
            return (firstDigit == 1 ? "" : firstDigit - 1) + "9" + nines;
        } else if (endToNines) {
            return x;
        } else {
            String newXPostfix = computeMaxDigitSumNumber(xPostfix);
            newXPostfix = fillZerosToLen(newXPostfix, len - 2);
            if (computeDigitSum(newXPostfix) >= 9 * (len - 2) - 1) {
                return firstDigit + "" + secondDigit + newXPostfix;
            } else {
                return (firstDigit * 10 + secondDigit - 1) + nines;
            }
        }
    }

    private static int computeDigitSum(String x) {
        int digitSum = 0;
        for (int i = 0; i < x.length(); ++i) {
            digitSum += x.charAt(i) - '0';
        }
        return digitSum;
    }

    private static String repeatChar(char c, int count) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; ++i) {
            sb.append(c);
        }
        return sb.toString();
    }

    private static String fillZerosToLen(String x, int len) {
        return repeatChar('0', len - x.length()) + x;
    }

}


import java.util.Scanner;

/**
 *
 * @author aselvarajah
 */
public class Days {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int day = scanner.nextInt();
	int day2 =day;
    int lessDay =0;
    int maxDay =0;

            while (day>0){
                if((day - 6) >= 0){
                    day = day-6;
                    lessDay++;
                    if((day - 1) >= 0){
                        day = day-1;
                        lessDay++;
                    }
                    else
                        break;
                }
                else
                    break;
            }

    	 if((day2 - 1) >= 0){
             day2 = day2-1;
             maxDay++;
         }
         while (day2>0){
             if((day2 - 1) >= 0){
                 day2 = day2-1;
                 maxDay++;
                 if((day2 - 6) >= 0){
                     day2 = day2-6;
                     maxDay++;
                 }
                 else
                     break;
             }
             else
                 break;
         }
         System.out.println(lessDay + " " +maxDay);

}

}


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

public class D{
    private void solve() {
        long n=nextLong();
        long ans=0;
        for(int i=1;i<=n-2;i++){
            ans=ans+(i+1)*(i+2);
        }
        writer.println(ans);
    }

    public static void main(String[] args) {
        new D().run();
    }
    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    private void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            writer = new PrintWriter(System.out);
            tokenizer = null;
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

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

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

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


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

public class practice {
    public static void merge(int arr[], int l, int m, int r) {
        // Find sizes of two subarrays to be merged
        int n1 = m - l + 1;
        int n2 = r - m;

        /* Create temp arrays */
        int L[] = new int[n1];
        int R[] = new int[n2];

        /*Copy data to temp arrays*/
        for (int i = 0; i < n1; ++i)
            L[i] = arr[l + i];
        for (int j = 0; j < n2; ++j)
            R[j] = arr[m + 1 + j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays
        int i = 0, j = 0;

        // Initial index of merged subarry array
        int k = l;
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                arr[k] = L[i];
                i++;
            } else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        /* Copy remaining elements of L[] if any */
        while (i < n1) {
            arr[k] = L[i];
            i++;
            k++;
        }

        /* Copy remaining elements of R[] if any */
        while (j < n2) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    // Main function that sorts arr[l..r] using
    // merge()
    public static void sort(int arr[], int l, int r) {
        if (l < r) {
            // Find the middle point
            int m = (l + r) / 2;

            // Sort first and second halves
            sort(arr, l, m);
            sort(arr, m + 1, r);

            // Merge the sorted halves
            merge(arr, l, m, r);
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
         int d = Integer.parseInt(st.nextToken());
        ArrayList<Integer>A = new ArrayList<>();
        String s = br.readLine();
       for(int i=0;i<n;i++){
           int b = Character.getNumericValue(s.charAt(i));
           if(b == 1){
               A.add(i+1);
           }
       }
       int jump = 0;
       boolean flag = true;
       for(int i=0;i<A.size()-1;){
           boolean check = false;
           int x = A.get(i);
           while (i<A.size()-1 && (A.get(i+1)-x)<=d){
               i++;
               check = true;
           }
           if(check){
               jump++;
           }
           else{
               flag = false;
               break;
           }
       }
       if(flag){
           System.out.println(jump);
       }
       else{
           System.out.println(-1);
       }
    }
}

class sort implements Comparator<ArrayList<Long>> {

    @Override
    public int compare(ArrayList<Long> o1, ArrayList<Long> o2) {
        int c = o1.get(2).compareTo(o2.get(2));
        return c;
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] S = in.readLine().split(" ");
        long[] A = new long[4];
        for (int i = 0; i < 4; i++)
            A[i] = Integer.parseInt(S[i]);
        S = in.readLine().split(" ");
        Queue<long[]> Q = new LinkedList<long[]>();
        Q.add(A);
        long min = Long.MAX_VALUE;
        while (!Q.isEmpty()) {
            long[] temp = Q.poll();
            if (temp.length == 1) {
                min = Math.min(min, temp[0]);
            }
            for (int i = 0; i < temp.length; i++)
                for (int j = 0; j < temp.length; j++) {
                    if (i == j)
                        continue;
                    long[] temp2 = new long[temp.length - 1];
                    if (S[4 - temp.length].equals("*"))
                        temp2[0] = temp[i] * temp[j];
                    else
                        temp2[0] = temp[i] + temp[j];
                    int c = 1;
                    for (int k = 0; k < temp.length; k++)
                        if (k != i && k != j)
                            temp2[c++] = temp[k];
                    Q.add(temp2);
                }
        }
        System.out.println(min);
    }
}


import java.util.*;

public class cf109b {
	static ArrayList<Long> lucky = new ArrayList<Long>();
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		genLucky(0,11);
		Collections.sort(lucky);
		long pl = in.nextLong();
		long pr = in.nextLong();
		long vl = in.nextLong();
		long vr = in.nextLong();
		int k = in.nextInt();
		double ret = 0;
		for(int i=0; i<lucky.size()-k-2; i++) {
			//assume p is lower
			//probability that p got in the interval (lucky[i],lucky[i+1]]
			long lo = Math.max(lucky.get(i)+1, pl);
			long hi = Math.min(lucky.get(i+1), pr);
			double p = Math.max(0,(hi-lo+1.)/(pr-pl+1));
			//probability that v got in the interval [lucky[i+k],lucky[i+k+1)
			lo = Math.max(lucky.get(i+k),vl);
			hi = Math.min(lucky.get(i+k+1)-1,vr);
			double v = Math.max(0,(hi-lo+1.)/(vr-vl+1));
			ret += p*v;

			//assume v is lower
			//probability that v got in the interval (lucky[i],lucky[i+1]]
			lo = Math.max(lucky.get(i)+1, vl);
			hi = Math.min(lucky.get(i+1), vr);
			v = Math.max(0,(hi-lo+1.)/(vr-vl+1));
			//probability that p got in the interval [lucky[i+k],lucky[i+k+1)
			lo = Math.max(lucky.get(i+k),pl);
			hi = Math.min(lucky.get(i+k+1)-1,pr);
			p = Math.max(0,(hi-lo+1.)/(pr-pl+1));
			ret += p*v;

			//remove double counting (probability they got the same)
			if(k==1) {
				lo = Math.max(lucky.get(i), vl);
				hi = Math.min(lucky.get(i), vr);
				v = Math.max(0,(hi-lo+1.)/(vr-vl+1));
				lo = Math.max(lucky.get(i),pl);
				hi = Math.min(lucky.get(i),pr);
				p = Math.max(0,(hi-lo+1.)/(pr-pl+1));
				ret -= p*v;
			}
		}
		System.out.printf("%.12f%n", ret);
	}
	static void genLucky(long cur, long left) {
		if(left == 0) return;
		lucky.add(cur);
		genLucky(cur*10+4,left-1);
		genLucky(cur*10+7,left-1);
	}
}


// Problem: A. Elevator or Stairs?
// Contest: Codeforces - Mail.Ru Cup 2018 Round 1
// URL: https://codeforces.com/problemset/problem/1054/A
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

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

public class Main {

	static PrintWriter out;
	static FastReader fr;
	// make it false if Multiple test case is not in the question
	static boolean multipleTC = false;
	static int TestCase = 1;

	// for pre processing if needed
	void pre() throws Exception {
	}

	public static void main(String[] args) throws Exception {

		new Main().run();
	}

	// input output handled here
	private Object solve() throws Exception {
		// code
		int y = fr.ni(), x = fr.ni(), z = fr.ni(), t1 = fr.ni(), t2 = fr.ni(), t3 = fr.ni();
		int timeElv = (Math.abs(y - z) * t2 + 2 * t3) + Math.abs(x - y) * t2 + t3;
		int timeStr = Math.abs(y - x) * t1;
		// deb(timeElv, timeStr);
		if (timeElv <= timeStr)
			return "YES";
		return "NO";
	}

	void run() throws Exception {
		// long start_time = System.nanoTime();

		try {
			fr = new FastReader("in0.txt");
			out = new PrintWriter("out0.txt");
		} catch (Exception e) {
			fr = new FastReader();
			out = new PrintWriter(System.out);
		}
		pre();
		StringBuilder print = new StringBuilder("");

		int T = (multipleTC) ? fr.ni() : 1;
		for (int t = 1; t <= T; t++) {
			TestCase = t;
			print.append(solve()).append("\n");
		}

		p(print);
		// long end_time = System.nanoTime();
		// System.out.printf("Running Time in sec : %2.10f", (double) (end_time -
		// start_time) * (double) 1e-9);

		out.flush();
		out.close();
	}

	static void p(Object o) {
		out.print(o);
	}

	static void pln(Object o) {
		out.println(o);
	}

	static void psp(Object o) {
		out.print(o + " ");
	}

	static void pnf(Object o) {
		out.println(o);
		out.flush();
	}

	static void deb(Object... x) {
		System.out.print("#" + TestCase + " = ");
		for (int i = 0; i < x.length - 1; i++)
			System.out.print(x[i] + " , ");
		System.out.println(x[x.length - 1]);

	}

	static void in(int a) throws Exception {
		a = fr.ni();
	}

	static void in(long a) throws Exception {
		a = fr.ni();
	}

	static void in(String[] a) throws Exception {
		a = fr.nln().trim().split(" ");
	}

	static void in(String a) throws Exception {
		a = fr.next();
	}

	static void in(int a[]) throws Exception {
		for (int i = 0; i < a.length; i++) {
			a[i] = fr.ni();
		}
	}

	static void in(long a[]) throws Exception {
		for (int i = 0; i < a.length; i++) {
			a[i] = fr.nl();
		}
	}

	static void in(int a[][]) throws Exception {
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[0].length; j++) {
				a[i][j] = fr.ni();
			}
		}
	}

	class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

		public FastReader(String s) throws Exception {
			br = new BufferedReader(new FileReader(s));
		}

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

		String nextLine() throws Exception {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				throw new Exception(e.toString());
			}
			return str;
		}

		String n() throws Exception {
			return fr.next();
		}

		String nln() throws Exception {
			return fr.nextLine().trim();
		}

		int ni() throws Exception {
			return Integer.parseInt(fr.next());
		}

		long nl() throws Exception {
			return Long.parseLong(fr.next());
		}

		double nd() throws Exception {
			return Double.parseDouble(fr.next());
		}

		int[] nextIntArray(int n) throws Exception {
			int[] a = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = fr.ni();
			}
			return a;
		}

		long[] nextLongArray(int n) throws Exception {
			long[] a = new long[n];
			for (int i = 0; i < n; i++) {
				a[i] = fr.nl();
			}
			return a;
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public final class check2{

	public static void main(String args[]){

		Scanner s=new Scanner(System.in);
		long x=s.nextLong();
		long y=s.nextLong();
		double result=(Math.log(x)/x)-(Math.log(y)/y);
		if(result<0) {
			System.out.println("<");
		}else if(result>0) {
			System.out.println(">");
		}else {
			System.out.println("=");
		}
	}
}


import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
import java.text.DecimalFormat;
import java.lang.reflect.Array;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
public class Codeforces{
	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long MOD = (long)(1e9+7);
	static long MOD2 = MOD*MOD;
	//static long MOD = 998244353;
	static FastReader sc = new FastReader();
	static int pInf = Integer.MAX_VALUE;
	static int nInf = Integer.MIN_VALUE;
	public static void main(String[] args){
		int test = 1;
		//test = sc.nextInt();
		while(test-->0){
			long a = sc.nextLong();
			long b = sc.nextLong();
			long n = sc.nextLong();
			long x = sc.nextLong();
			if(a==1) {
				out.println(add(x, mul(n, b)));
				continue;
			}
			long a1 = mul(fastExpo(a, n), x);
			long a2 = mul(b, mul((fastExpo(a, n)-1),finextDoubleMMI_fermat(a-1, (int)MOD)));
			out.println(add(a1, a2));
		}
		out.close();
	}
	public static long solve(long a, long b, long x, long y, long n) {
		if(a-x<n) {
			n = n-(a-x);
			a = x;
			b = Math.max(y, b-n);
		}
		else {
			a = a-n;
		}
		return a*b;
	}
	public static int lowerBound(int key, ArrayList<Integer> A) {
		int s = 0;
		int e = A.size()-1;
		if(e==-1) {
			return 0;
		}
		int ans = -1;
		while(s<=e) {
			int m = s+(e-s)/2;
			if(A.get(m)>=key) {
				ans = m;
				e = m-1;
			}
			else {
				s = m+1;
			}
		}
		return ans==-1?s:ans;
	}
	public static int upperBound(int key, ArrayList<Integer> A) {
		int s = 0;
		int e = A.size()-1;
		if(e==-1) {
			return 0;
		}
		int ans = -1;
		while(s<=e) {
			int m = s+(e-s)/2;
			if(A.get(m)>key) {
				ans = m;
				e = m-1;
			}
			else {
				s = m+1;
			}
		}
		return ans==-1?s:ans;
	}
	public static long c2(long n) {
		if((n&1)==0) {
			return mul(n/2, n-1);
		}
		else {
			return mul(n, (n-1)/2);
		}
	}
	public static long mul(long a, long b){
	    return ((a%MOD)*(b%MOD))%MOD;
	}
	public static long add(long a, long b){
	    return ((a%MOD)+(b%MOD))%MOD;
	}
	public static long sub(long a, long b){
	    return ((a%MOD)-(b%MOD))%MOD;
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Integer.lowestOneBit(i)   Equals k where k is the position of the first one in the binary
//Integer.highestOneBit(i)  Equals k where k is the position of the last one in the binary
//Integer.bitCount(i)       returns the number of one-bits
//Collections.sort(A,(p1,p2)->(int)(p2.x-p1.x)) To sort ArrayList in descending order wrt values of x.
//            Arrays.parallelSort(a,new Comparator<TPair>() {
//      		public int compare(TPair a,TPair b) {
//        			if(a.y==b.y) return a.x-b.x;
//        			return b.y-a.y;
//        		}
//        	});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PrimeFactors
    public static ArrayList<Long> primeFactors(long n) {
        ArrayList<Long> arr = new ArrayList<>();
        if (n % 2 == 0)
            arr.add((long) 2);
        while (n % 2 == 0)
            n /= 2;
        for (long i = 3; i <= Math.sqrt(n); i += 2) {
            int flag = 0;
            while (n % i == 0) {
                n /= i;
                flag = 1;
            }
            if (flag == 1)
                arr.add(i);
        }
        if (n > 2)
            arr.add(n);
        return arr;
    }
//Pair Class
	static class Pair implements Comparable<Pair>{
		int x;
		int y;
		int len;
		public Pair(int x, int y) {
			this.x = x;
			this.y = y;
			this.len = y-x+1;
		}
		/*@Override
		public int compareTo(Pair o) {
			if(this.x==o.x){
			    return (this.y-o.y);
			}
			return (this.x-o.x);
		}*/
		@Override
		public int compareTo(Pair o) {
			if(this.len==o.len) {
				return this.x-o.x;
			}
			else {
				return o.len-this.len;
			}
		}
	}
	static class TPair implements Comparable<TPair>{
		int two;
		int three;
		int prime;
		public TPair(int two, int three, int prime) {
			this.two = two;
			this.three = three;
			this.prime = prime;
		}
		@Override
		public int compareTo(TPair o) {
			if(this.three==o.three){
			    return (this.two-o.two);
			}
			return -1*(this.three-o.three);
		}
	}
//nCr
	static long ncr(long n, long k) {
        long ret = 1;
        for (long x = n; x > n - k; x--) {
            ret *= x;
            ret /= (n - x + 1);
        }

        return ret;
    }
	static long finextDoubleMMI_fermat(long n,int M)
    {
        return fastExpo(n,M-2);
    }

    static long nCrModPFermat(int n, int r, int p)
    {
        if (r == 0)
            return 1;
        long[] fac = new long[n+1];
        fac[0] = 1;
        for (int i = 1 ;i <= n; i++)
            fac[i] = fac[i-1] * i % p;
        return (fac[n]* finextDoubleMMI_fermat(fac[r], p)% p * finextDoubleMMI_fermat(fac[n-r], p) % p) % p;
    }
//Kadane's Algorithm
    static long maxSubArraySum(ArrayList<Long> a) {
    	if(a.size()==0) {
    		return 0;
    	}
    	long max_so_far = a.get(0);
    	long curr_max = a.get(0);
    	for (int i = 1; i < a.size(); i++) {
           curr_max = Math.max(a.get(i), curr_max+a.get(i));
           max_so_far = Math.max(max_so_far, curr_max);
    	}
    	return max_so_far;
    }
//Shuffle Sort
    static final Random random=new Random();
	static void ruffleSort(int[] a) {
		int n=a.length;//shuffle, then sort
		for (int i=0; i<n; i++) {
			int oi=random.nextInt(n), temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}
//Merge Sort
	static void merge(long arr[], int l, int m, int r)
    {
        // Find sizes of two subarrays to be merged
        int n1 = m - l + 1;
        int n2 = r - m;

        /* Create temp arrays */
        long L[] = new long [n1];
        long R[] = new long [n2];

        /*Copy data to temp arrays*/
        for (int i=0; i<n1; ++i)
            L[i] = arr[l + i];
        for (int j=0; j<n2; ++j)
            R[j] = arr[m + 1+ j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays
        int i = 0, j = 0;

        // Initial index of merged subarry array
        int k = l;
        while (i < n1 && j < n2)
        {
            if (L[i] <= R[j])
            {
                arr[k] = L[i];
                i++;
            }
            else
            {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        /* Copy remaining elements of L[] if any */
        while (i < n1)
        {
            arr[k] = L[i];
            i++;
            k++;
        }

        /* Copy remaining elements of R[] if any */
        while (j < n2)
        {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    // Main function that sorts arr[l..r] using
    // merge()
    static void sort(long arr[], int l, int r)
    {
        if (l < r)
        {
            // Find the middle point
            int m = (l+r)/2;

            // Sort first and second halves
            sort(arr, l, m);
            sort(arr , m+1, r);

            // Merge the sorted halves
            merge(arr, l, m, r);
        }
    }
//Brian Kernighans Algorithm
    static long countSetBits(long n){
        if(n==0) return 0;
        return 1+countSetBits(n&(n-1));
    }
//Factorial
    static long factorial(long n){
        if(n==1) return 1;
        if(n==2) return 2;
        if(n==3) return 6;
        return n*factorial(n-1);
    }
//Euclidean Algorithm
    static long gcd(long A,long B){
        if(B==0) return A;
        return gcd(B,A%B);
    }
//Modular Exponentiation
    static long fastExpo(long x,long n){
        if(n==0) return 1;
        if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
        return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
    }
//AKS Algorithm
    static boolean isPrime(long n){
        if(n<=1) return false;
        if(n<=3) return true;
        if(n%2==0 || n%3==0) return false;
        for(int i=5;i<=Math.sqrt(n);i+=6)
            if(n%i==0 || n%(i+2)==0) return false;
        return true;
    }
//Reverse an array
    static <T> void reverse(T arr[],int l,int r){
    	Collections.reverse(Arrays.asList(arr).subList(l, r));
    }
  //Print array
    static void print1d(int arr[]) {
    	out.println(Arrays.toString(arr));
    }
    static void print2d(int arr[][]) {
    	for(int a[]: arr) out.println(Arrays.toString(a));
    }
//Sieve of eratosthenes
    static int[] findPrimes(int n){
        boolean isPrime[]=new boolean[n+1];
        ArrayList<Integer> a=new ArrayList<>();
        int result[];
        Arrays.fill(isPrime,true);
        isPrime[0]=false;
        isPrime[1]=false;
        for(int i=2;i*i<=n;++i){
            if(isPrime[i]==true){
                for(int j=i*i;j<=n;j+=i) isPrime[j]=false;
            }
        }
        for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i);
        result=new int[a.size()];
        for(int i=0;i<a.size();i++) result[i]=a.get(i);
        return result;

    }
//Indivisual factors of all nos till n
    static ArrayList<Integer>[] indiFactors(int n){
    	ArrayList<Integer>[] A = new ArrayList[n+1];
    	for(int i = 0; i <= n; i++) {
    		A[i] = new ArrayList<>();
    	}
    	int[] sieve = new int[n+1];
    	for(int i=2;i<=n;i++) {
       		if(sieve[i]==0) {
       			for(int j=i;j<=n;j+=i) if(sieve[j]==0) {
       				//sieve[j]=i;
       				A[j].add(i);
       			}
       		}
       	}
    	return A;
    }
//Segmented Sieve
    static boolean[] segmentedSieve(long l, long r){
    	boolean[] segSieve = new boolean[(int)(r-l+1)];
    	Arrays.fill(segSieve, true);
    	int[] prePrimes = findPrimes((int)Math.sqrt(r));
    	for(int p:prePrimes) {
    		long low = (l/p)*p;
    		if(low < l) {
    			low += p;
    		}
    		if(low == p) {
    			low += p;
    		}
    		for(long j = low; j<= r; j += p) {
    			segSieve[(int) (j-l)] = false;
    		}
    	}
    	if(l==1) {
    		segSieve[0] = false;
    	}
    	return segSieve;
    }
//Euler Totent function
    static long countCoprimes(long n){
        ArrayList<Long> prime_factors=new ArrayList<>();
        long x=n,flag=0;
        while(x%2==0){
            if(flag==0) prime_factors.add(2L);
            flag=1;
            x/=2;
        }
        for(long i=3;i*i<=x;i+=2){
            flag=0;
            while(x%i==0){
                if(flag==0) prime_factors.add(i);
                flag=1;
                x/=i;
            }
        }
        if(x>2) prime_factors.add(x);
        double ans=(double)n;
        for(Long p:prime_factors){
            ans*=(1.0-(Double)1.0/p);
        }
        return (long)ans;
    }
	static long modulo = (long)1e9+7;
	public static long modinv(long x){
	    return modpow(x, modulo-2);
	}
	public static long modpow(long a, long b){
	    if(b==0){
	        return 1;
	    }
	    long x = modpow(a, b/2);
	    x = (x*x)%modulo;
	    if(b%2==1){
	        return (x*a)%modulo;
	    }
	    return x;
	}
	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;
		//it reads the data about the specified point and divide the data about it ,it is quite fast
		//than using direct

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

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());//converts string to integer
		}

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

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

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


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

public class Main{
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        AC solver = new AC();
        solver.solve(in, out);
        out.close();
    }
}

class AC {
    int n , m;
    boolean judge(int x,int y) {
        return 1<=x && x <= n && 1 <= y && y <= m;
    }
    int x , y  , dx , dy;
    long  go()
    {
         int delta;
         if(dx < 0) {
             if(dy < 0)  {
                 delta = Math.min(x-1, y-1);
             } else {
                 delta = Math.min(m-y, x-1);
             }
         } else {
             if(dy < 0) {
                 delta = Math.min(n-x, y-1);
             } else {
                 delta = Math.min(n-x,m-y);
             }
         }
         x += dx * delta;
         y += dy * delta;
         if(x+dx<1 || x+dx>n) dx *= -1;
         if(y+dy<1 || y+dy>m) dy *= -1;
         return (long)x*dx*1000000 + y*dy;
    }
    public void solve(InputReader in, PrintWriter out) {
          int x0 , y0;
          String cmd;
          HashSet<Long> mp = new HashSet<Long>();
          HashSet<Long> M = new HashSet<Long>();
          n = in.nextInt();
          m = in.nextInt();
          x0 = in.nextInt(); y0 = in.nextInt();
          cmd = in.next();
          int tot = n + m - 2;
          if(cmd.charAt(0)=='D') {
              dx = 1;
          } else dx = -1;
          if(cmd.charAt(1)=='R') {
              dy = 1;
          } else dy = -1;
          long  ans = 1;
          x = x0 ; y = y0;
          if(x0==1 || x0==n || y0==1 || y0==m){
              M.add((long)x0*1000000+y0);
              tot --;
          }
          while(true) {
              long  tmp = go();
              if(mp.contains(tmp)){
                 ans = -1;
                 break;
              } else {
                  mp.add(tmp);
              }
              ans += Math.abs(x - x0);
              //out.println(x+" "+y);
              x0 = x ; y0 = y ;

              long flag = (long)x0*1000000+y0;
              if(!M.contains(flag)) {
                // out.println(tot);
                  M.add(flag);
                  if(--tot == 0) break;
              }
          }
          out.println(ans);
    }
}
class InputReader {
    BufferedReader reader;
    StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
        tokenizer = null;
    }

    public String next() {
        if (!hasNext())
            throw new RuntimeException();
        return tokenizer.nextToken();
    }

    boolean hasNext() {
        while (tokenizer == null || !tokenizer.hasMoreTokens())
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (Exception e) {
                return false;
            }
        return true;
    }

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

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

    public long nextLong() {
        return Long.parseLong(next());
    }
    public BigInteger nextBigInteger() {
        return new BigInteger(next());
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;

public class First {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);
        StringTokenizer st = new StringTokenizer(reader.readLine());
        int n = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        ArrayList<Integer> arrayList = new ArrayList<>();
        int time = 0;
        st = new StringTokenizer(reader.readLine());
        for(int  i = 0; i < n; ++i){
            int nw = Integer.parseInt(st.nextToken());
            time += nw;
            int razn = time - M;
            int ind = arrayList.size()-1;
            int count = 0;
            while(razn > 0){
                razn -= arrayList.get(ind);
                --ind;
                ++count;
            }
            arrayList.add(nw);
            Collections.sort(arrayList);
            writer.print(count + " ");
        }
        writer.close();
    }
}


import java.util.Scanner;

public class ER82_D {
	private static final int N = 200001;
	private static final int MOD = 998244353;

	public static void main(String[] args) {
		int[] fact = new int[N];
		fact[0] = 1;
		for (int i = 1; i < N; i++) {
			fact[i] = mul(fact[i-1], i);
		}

		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();

		int ans = 0;

		if (n > 2) {
			ans = mul(C(m, n-1, fact), mul(n - 2, binpow(2, n - 3)));
		}
		System.out.println(ans);
	}

	private static int add(int x, int y) {
		x += y;

		return x % MOD;

	}

	private static int mul(int x, int y) {
		int res = (int) (((long) x * y) % MOD);
		return res;

	}

	private static int binpow(int x, int y) {
		int z = 1;
		while (y > 0) {
			if (y % 2 != 0)
				z = mul(z, x);
			x = mul(x, x);
			y >>= 1;
		}
		return z;
	}

	private static int inv(int x) {
		return binpow(x, MOD - 2);
	}

	private static int devide(int x, int y) {
		return mul(x, inv(y));
	}

	private static int C(int n, int k, int[] fact) {
		return devide(fact[n], mul(fact[k], fact[n-k]));
	}
}


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

public class B1033 {

    static ArrayList<Long> list;
    public static void main(String[] args)throws IOException {
        BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

        list = sieveOfEratosthenes();
        //System.out.println(list);
        int testCase = Integer.parseInt(inp.readLine());
        for(int t=0;t<testCase;t++){
            String[] s1 = inp.readLine().split(" ");
            long a = Long.parseLong(s1[0]);
            long b =Long.parseLong(s1[1]);

            long c = a+b;
            long d = a-b;

            //System.out.println(d);

            if(d!=1L){
                System.out.println("NO");
            }
            else{

                if(isPrime(c)){
                    System.out.println("YES");
                }
                else{
                    System.out.println("NO");
                }

            }

        }

    }
    static ArrayList<Long> sieveOfEratosthenes() {
        int n = 1000000;
        ArrayList<Long> list = new ArrayList<>();
        boolean[] prime = new boolean[n];

        for(int p = 2; p*p <n; p++) {
            if(!prime[p]) {
                for(int i = p*p; i < n; i += p)
                    prime[i] = true;
            }
        }

        for(int i = 2; i < n; i++) {
            if(!prime[i]) {
                list.add((long) i);
            }
        }
        return list;
    }
    static boolean isPrime(long a){
        int b = (int) Math.sqrt(a);
        //System.out.println(b);
        for(int i=0;i<list.size();i++){
            if(list.get(i)<=(long)b) {
                if (a % list.get(i) == 0) {
                    return false;
                }
            }
            else{
                break;
            }
        }
        return true;
    }
}


import java.io.*;
import java.util.*;
public class first
{
	public static void main(String[] args)throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		PrintWriter pw=new PrintWriter(System.out);
		String s[]=br.readLine().split(" ");
		long n=Long.parseLong(s[0]);
		long a=Long.parseLong(s[1]);
		long b=Long.parseLong(s[2]);
		long c=Long.parseLong(s[3]);
		long min=Long.MAX_VALUE;
		if(n%4==0)
		min=0;
		else if(n%4==1)
		{
			min=Math.min(3*a,Math.min(a+b,c));
		}
		else if(n%4==2)
		{
			min=Math.min(b,Math.min(2*a,2*c));

		}
		else
		{
			min=Math.min(a,Math.min(b+c,3*c));
		}

		pw.println(min);
		pw.flush();

	}
}


import java.math.BigInteger;
import java.util.Scanner;

public class Main
{
    static BigInteger fac[]=new BigInteger[1005];
    static BigInteger w[]=new BigInteger[6];
    static BigInteger get(int n,int m)
    {
        return fac[n].divide(fac[m]).divide(fac[n-m]);
    }
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int k=sc.nextInt();
        fac[0]=BigInteger.ONE;
        for(int i=1;i<=n;i++)
            fac[i]=fac[i-1].multiply(BigInteger.valueOf(i));
        w[0]=BigInteger.ONE;
        w[1]=BigInteger.ZERO;
        w[2]=BigInteger.ONE;
        for(int i=3;i<=5;i++)
            w[i]=BigInteger.valueOf(i-1).multiply(w[i-1].add(w[i-2]));

        BigInteger ans=BigInteger.ZERO;
        for(int i=n-k;i<=n;i++)
        {
            ans=ans.add(get(n,i).multiply(w[n-i]));
        }
        System.out.println(ans);
    }
}


import java.lang.reflect.Array;
import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class main implements Runnable {

    static ArrayList<Integer> adj[];

    static void Check2(int n) {
        adj = new ArrayList[n + 1];
        for (int i = 0; i <= n; i++) {
            adj[i] = new ArrayList<>();
        }

    }
    static void add(int i, int j) {
        adj[i].add(j);
        adj[j].add(i);
    }

    public static void main(String[] args) {
        new Thread(null, new main(), "Check2", 1 << 26).start();// to increse stack size in java
    }
    static long mod = (long) (1e9 + 7);
    public void run() {
                                /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        //Scanner in=new Scanner(System.in);

           InputReader in = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);

        char c[]=in.next().toCharArray();
      int max=10;

      for(int i=0;i<10;i++){

            for (int j=0;j<10;j++){
                for(int k=0;k<10;k++){

                    for(int l=0;l<10;l++)
                    {
                        for(int m=0;m<10;m++){
                            for(int n=0;n<10;n++){
                                int co=0;

                                if(i+j+k==l+m+n){
                                    if(i!=c[0]-48)co++;
                                    if(j!=c[1]-48)co++;
                                    if(k!=c[2]-48)co++;
                                    if(l!=c[3]-48)co++;
                                    if(m!=c[4]-48)co++;
                                    if(n!=c[5]-48)co++;
                                    max=min(max,co);
                                }

                            }
                        }
                    }

                }
            }

      }
      w.println(max);

        w.close();
    }

    static class cmp implements Comparator<pair>{

        public int compare(pair o1,pair o2)

        {

            if(o1.val!=o2.val)
                return o1.val<o2.val?-1:o1.val>o2.val?1:0;
            else
                return -(o1.type-o2.type);

        }

    }
    static class pair {
        long val;
        int type;
        pair(long a,int type){
            val=a;
            this.type=type;
        }
    }

    static long power(long x,long y){
        if(y==0)return 1%mod;
        if(y==1)return x%mod;

        long res=1;
        x=x%mod;
        while(y>0){

            if((y%2)!=0){
                res=(res*x)%mod;
            }

            y=y/2;
            x=(x*x)%mod;
        }

        return res;

    }

    static  int gcd(int a,int b){

        if(b==0)return a;
        return gcd(b,a%b);
    }

    static  void sev(int a[],int n){

        for(int i=2;i<=n;i++)a[i]=i;
        for(int i=2;i<=n;i++){

            if(a[i]!=0){
                for(int j=2*i;j<=n;){

                    a[j]=0;
                    j=j+i;
                }
            }

        }

    }

    static class node{

        int y;
        int val;

        node(int a,int b){

            y=a;
            val=b;

        }

    }

    static 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 String nextLine()
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            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 long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long 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 double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

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

}


import java.util.*;
import java.awt.List;
import java.io.*;
import java.lang.*;
import java.lang.reflect.Array;
public class c4
{

	public static int mod = (int)Math.pow(10, 9) + 7;
    public static int n;
    public static int m;
    public static int[][][] a;
    public static String[] st;
    public static void main(String[] args)
    {
        InputReader in = new InputReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        // Code starts..

        long n = in.nextLong();
        int m = in.nextInt();
        long[] a = new long[m];

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

        long[] b = new long[m];
        for(int i=0; i<m; i++)
        {
        	int t = ((i)%m * (i)%m)%m;
        	b[t] += a[i];
        }
        long ans = 0;
        for(int i=0; i<m; i++)
        {

        	if(i==0)
        	{
        		ans += (b[i]*(b[i]));

        	}
        	else
        	{
        		ans += b[i] * b[m-i];
        	}

        }
        pw.println(ans);

        // code ends...

        pw.flush();
        pw.close();
    }

    public static void factSieve(int[] fact, long n) {

        for (int i = 2; i <= n; i += 2)
            fact[i] = 2;

        for (int i = 3; i <= n; i += 2) {
            if (fact[i] == 0) {
                fact[i] = i;

                for (int j = i; (long) j * i <= n; j++) {
                    fact[(int) ((long) i * j)] = i;
                }
            }
        }

        /*
         * int k = 1000; while(k!=1) { System.out.print(a[k]+" "); k /= a[k];
         *
         * }
         */
    }

    public static int gcd(int p2, int p22) {
        if (p2 == 0)
            return (int) p22;
        return gcd(p22 % p2, p2);
    }

    public static void nextGreater(long[] a, int[] ans) {

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

        for (int i = 1; i < a.length; i++) {

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (a[s] < a[i]) {
                    ans[s] = i;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (a[s] >= a[i])
                    stk.push(s);
            }

            stk.push(i);

        }
        return;

    }

    public static void nextGreaterRev(long[] a, int[] ans) {

        int n = a.length;
        int[] pans = new int[n];
        Arrays.fill(pans, -1);
        long[] arev = new long[n];
        for (int i = 0; i < n; i++)
            arev[i] = a[n - 1 - i];

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

        for (int i = 1; i < n; i++) {

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (arev[s] < arev[i]) {
                    pans[s] = n - i - 1;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (arev[s] >= arev[i])
                    stk.push(s);
            }

            stk.push(i);

        }

        // for(int i=0; i<n; i++)
        // System.out.print(pans[i]+" ");

        for (int i = 0; i < n; i++)
            ans[i] = pans[n - i - 1];

        return;

    }

    public static void nextSmaller(long[] a, int[] ans) {

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

        for (int i = 1; i < a.length; i++) {

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (a[s] > a[i]) {
                    ans[s] = i;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (a[s] <= a[i])
                    stk.push(s);
            }

            stk.push(i);

        }
        return;

    }

    public static long lcm(int[] numbers) {
        long lcm = 1;
        int divisor = 2;
        while (true) {
            int cnt = 0;
            boolean divisible = false;
            for (int i = 0; i < numbers.length; i++) {
                if (numbers[i] == 0) {
                    return 0;
                } else if (numbers[i] < 0) {
                    numbers[i] = numbers[i] * (-1);
                }
                if (numbers[i] == 1) {
                    cnt++;
                }
                if (numbers[i] % divisor == 0) {
                    divisible = true;
                    numbers[i] = numbers[i] / divisor;
                }
            }
            if (divisible) {
                lcm = lcm * divisor;
            } else {
                divisor++;
            }
            if (cnt == numbers.length) {
                return lcm;
            }
        }
    }

    public static long fact(long n) {

        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        return factorial;
    }

    public static long choose(long total, long choose) {
        if (total < choose)
            return 0;
        if (choose == 0 || choose == total)
            return 1;
        return (choose(total - 1, choose - 1) + choose(total - 1, choose)) % mod;
    }

    public static int[] suffle(int[] a, Random gen) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int ind = gen.nextInt(n - i) + i;
            int temp = a[ind];
            a[ind] = a[i];
            a[i] = temp;
        }
        return a;
    }

    public static int[] sufflesort(int[] a) {
        int n = a.length;
        Random gen = new Random();
        for (int i = 0; i < n; i++) {
            int ind = gen.nextInt(n - i) + i;
            int temp = a[ind];
            a[ind] = a[i];
            a[i] = temp;
        }
        Arrays.sort(a);
        return a;
    }

    public static int floorSearch(int arr[], int low, int high, int x) {
        if (low > high)
            return -1;

        if (x > arr[high])
            return high;
        int mid = (low + high) / 2;

        if (mid > 0 && arr[mid - 1] < x && x < arr[mid])
            return mid - 1;

        if (x < arr[mid])
            return floorSearch(arr, low, mid - 1, x);

        return floorSearch(arr, mid + 1, high, x);
    }

    public static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }

    public static ArrayList<Integer> primeFactorization(int n) {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (int i = 2; i * i <= n; i++) {
            while (n % i == 0) {
                a.add(i);
                n /= i;
            }
        }
        if (n != 1)
            a.add(n);
        return a;
    }

    public static void sieve(boolean[] isPrime, int n) {
        for (int i = 1; i < n; i++)
            isPrime[i] = true;

        isPrime[0] = false;
        isPrime[1] = false;

        for (int i = 2; i * i < n; i++) {
            if (isPrime[i] == true) {
                for (int j = (2 * i); j < n; j += i)
                    isPrime[j] = false;
            }
        }
    }

    public static int lowerbound(ArrayList<Long> net, long c2) {
        int i = Collections.binarySearch(net, c2);
        if (i < 0)
            i = -(i + 2);
        return i;

    }

    public static int lowerboundArray(int[] dis, int c2) {
        int i = Arrays.binarySearch(dis, c2);
        if (i < 0)
            i = -(i + 2);
        return i;

    }

    public static int uperbound(ArrayList<Integer> list, int c2) {
        int i = Collections.binarySearch(list, c2);
        if (i < 0)
            i = -(i + 1);
        return i;

    }

    public static int uperboundArray(int[] dis, int c2) {
        int i = Arrays.binarySearch(dis, c2);
        if (i < 0)
            i = -(i + 1);
        return i;

    }

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

    public static long GCD(long a, long b) {
        if (b == 0)
            return a;
        else
            return GCD(b, a % b);
    }

    public static int d1;
    public static int p1;
    public static int q1;

    public static void extendedEuclid(int A, int B) {
        if (B == 0) {
            d1 = A;
            p1 = 1;
            q1 = 0;
        } else {
            extendedEuclid(B, A % B);
            int temp = p1;
            p1 = q1;
            q1 = temp - (A / B) * q1;
        }
    }

    public static long LCM(long a, long b) {
        return (a * b) / GCD(a, b);
    }

    public static int LCM(int a, int b) {
        return (a * b) / GCD(a, b);
    }

    public static int binaryExponentiation(int x, int n) {
        int result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = result * x;
            x = x * x;
            n = n / 2;
        }
        return result;
    }

    public static int[] countDer(int n) {
        int der[] = new int[n + 1];

        der[0] = 1;
        der[1] = 0;
        der[2] = 1;

        for (int i = 3; i <= n; ++i)
            der[i] = (i - 1) * (der[i - 1] + der[i - 2]);

        // Return result for n
        return der;
    }

    static long binomialCoeff(int n, int k) {
        long C[][] = new long[n + 1][k + 1];
        int i, j;

        // Calculate value of Binomial Coefficient in bottom up manner
        for (i = 0; i <= n; i++) {
            for (j = 0; j <= Math.min(i, k); j++) {
                // Base Cases
                if (j == 0 || j == i)
                    C[i][j] = 1;

                // Calculate value using previosly stored values
                else
                    C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
            }
        }

        return C[n][k];
    }

    public static long binaryExponentiation(long x, long n) {
        long result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = result * x;
            x = (x % mod * x % mod) % mod;
            n = n / 2;
        }
        return result;
    }

    public static int modularExponentiation(int x, int n, int M) {
        int result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = (result * x) % M;
            x = (x * x) % M;
            n = n / 2;
        }
        return result;
    }

    public static long modularExponentiation(long x, long n, long M) {
        long result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = (result * x) % M;
            x = (x * x) % M;
            n = n / 2;
        }
        return result;
    }

    public static int modInverse(int A, int M) {
        return modularExponentiation(A, M - 2, M);
    }

    public static long sie(long A, long M) {
        return modularExponentiation(A, M - 2, M);
    }

    public static boolean isPrime(int n) {

        if (n <= 1)
            return false;
        if (n <= 3)
            return true;

        if (n % 2 == 0 || n % 3 == 0)
            return false;

        for (int i = 5; i * i <= n; i = i + 6) {
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }

        return true;
    }

    static class pair implements Comparable<pair>

    {
        Integer x, y;

        pair(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int compareTo(pair o) {
            int result = x.compareTo(o.x);
            if (result == 0)
                result = y.compareTo(o.y);

            return result;
        }

        public String toString() {
            return x + " " + y;
        }

        public boolean equals(Object o) {
            if (o instanceof pair) {
                pair p = (pair) o;
                return p.x == x && p.y == y;
            }
            return false;
        }

        public int hashCode() {
            return new Long(x).hashCode() * 31 + new Long(y).hashCode();
        }

    }

    static class triplet implements Comparable<triplet> {
        Integer x, y, z;

        triplet(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public int compareTo(triplet o) {
            int result = x.compareTo(o.x);
            if (result == 0)
                result = y.compareTo(o.y);
            if (result == 0)
                result = z.compareTo(o.z);

            return result;
        }

        public boolean equlas(Object o) {
            if (o instanceof triplet) {
                triplet p = (triplet) o;
                return x == p.x && y == p.y && z == p.z;
            }
            return false;
        }

        public String toString() {
            return x + " " + y + " " + z;
        }

        public int hashCode() {
            return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode();
        }
    }

    /*
     * static class node implements Comparable<node>
     *
     * { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; }
     *
     * public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0)
     * result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return
     * result; }
     *
     * @Override public int compareTo(node o) { // TODO Auto-generated method stub
     * return 0; } }
     */

    static class InputReader
	{

		private final InputStream stream;
		private final byte[] buf = new byte[8192];
		private int curChar, snumChars;
		private SpaceCharFilter filter;

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

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

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

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

		public int[] nextIntArray(int n)
		{
			int a[] = new int[n];
			for (int i = 0; i < n; i++)
			{
				a[i] = nextInt();
			}
			return a;
		}

		public String readString()
	    {
			int c = snext();
			while (isSpaceChar(c))
			{
				c = snext();
			}
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = snext();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public String nextLine()
		{
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = snext();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c)
		{
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c)
		{
			return c == '\n' || c == '\r' || c == -1;
		}

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

}


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;

@SuppressWarnings("Duplicates")
public class ProblemC {

    public static void main(String[] args) throws IOException{
        Reader sc = new Reader();
        PrintWriter pw = new PrintWriter(System.out);
        //Scanner sc = new Scanner(System.in);
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        long n1 = sc.nextInt();
        long n2 = sc.nextInt();
        if (n1 == 1 || n2 == 1 || n1 == n2){
            pw.println(0);
        } else {
            long aux = Math.min(n1,n2);
            n2 = Math.max(n1,n2);
            n1 = aux;
            // n1 < n2
            aux = n2-n1;
            long sol = 0;
            long min = n1*n2;
            HashSet<Long> set = new HashSet<>();
            for (long i = 1; i <= (long)Math.ceil(Math.sqrt(aux)); i++) {
                if (aux%i==0){
                    set.add(i);
                    set.add(aux/i);
                }
            }
            for (Long divs : set) {
                long rest = n1%divs;
                long  x = (divs-rest)%divs;
                long res = (n1+x)*(n2+x)/divs;
                if (res < min || (res == min && x < sol)){
                    sol = x;
                    min = res;
                }
            }
            pw.println(sol);
        }

        pw.flush();
    }

    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
}


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

public class Main {
    public static void main(String[] args){
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        solve(in, out);
        out.close();
    }

    static String reverse(String s) {
        return (new StringBuilder(s)).reverse().toString();
    }

    static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar)
    {
        factors[1]=1;
        int p;
        for(p = 2; p*p <=n; p++)
        {
            if(factors[p] == 0)
            {
                ar.add(p);
                factors[p]=p;
                for(int i = p*p; i <= n; i += p)
                    if(factors[i]==0)
                        factors[i] = p;
            }
        }
        for(;p<=n;p++){
            if(factors[p] == 0)
            {
                factors[p] = p;
                ar.add(p);
            }
        }
    }

    static void sort(int ar[]) {
        int n = ar.length;
        ArrayList<Integer> a = new ArrayList<>();
        for (int i = 0; i < n; i++)
            a.add(ar[i]);
        Collections.sort(a);
        for (int i = 0; i < n; i++)
            ar[i] = a.get(i);
    }

    static void sort1(long ar[]) {
        int n = ar.length;
        ArrayList<Long> a = new ArrayList<>();
        for (int i = 0; i < n; i++)
            a.add(ar[i]);
        Collections.sort(a);
        for (int i = 0; i < n; i++)
            ar[i] = a.get(i);
    }

    static void sort2(char ar[]) {
        int n = ar.length;
        ArrayList<Character> a = new ArrayList<>();
        for (int i = 0; i < n; i++)
            a.add(ar[i]);
        Collections.sort(a);
        for (int i = 0; i < n; i++)
            ar[i] = a.get(i);
    }

    static long ncr(long n, long r, long mod) {
        if (r == 0)
            return 1;
        long val = ncr(n - 1, r - 1, mod);
        val = (n * val) % mod;
        val = (val * modInverse(r, mod)) % mod;
        return val;
    }

    static long max[];
    static long lz[];

    // static void build(long a[], int v, int tl, int tr) {
    //     if (tl == tr) {
    //         max[v] = a[tl];

    //     } else {
    //         int tm = (tl + tr) / 2;
    //         build(a, v*2, tl, tm);
    //         build(a, v*2+1, tm+1, tr);
    //         max[v] = max[v*2] + max[v*2+1];
    //     }
    // }

    // static void push(int v, int tl, int tr){
    //     if(tl==tr){
    //         lz[v] = 0;
    //         return;
    //     }
    //     max[2*v] += lz[v];
    //     // max[2*v] %= m;
    //     max[2*v+1] += lz[v];
    //     // max[2*v+1] %= m;
    //     lz[2*v] += lz[v];
    //     lz[2*v] %= m;
    //     lz[2*v+1] += lz[v];
    //     lz[2*v+1] %= m;
    //     lz[v] = 0;
    // }

    static void update(int v, int tl, int tr, int l, int r, long val) {
        if(tl>r||tr<l)
            return;
        if(tl>=l&&tr<=r){
            max[v] = Math.max(val, max[v]);
            return;
        }
        int tm = ((tl + tr) >> 1);
        update(v*2, tl, tm, l, r, val);
        update(v*2+1, tm+1, tr, l, r, val);
        max[v] = Math.max(max[2*v],max[2*v+1]);
    }

    static long get(int v, int tl, int tr, int l, int r) {
        if(l>tr||r<tl)
            return 0;
        if (tl >= l && tr <= r) {
            return max[v];
        }
        int tm = ((tl + tr) >> 1);
        return Math.max(get(2*v, tl, tm, l, r), get(2*v+1, tm+1, tr, l, r));
    }

    // static int y = 0;

    static int parent[];
    static int rank[];

    static long m = 0;

    static int find_set(int v) {
        if (v == parent[v])
            return v;
        return find_set(parent[v]);
    }

    static void make_set(int v) {
        parent[v] = v;
        rank[v] = 1;
    }

    static void union_sets(int a, int b) {
        a = find_set(a);
        b = find_set(b);
        if (a != b) {
            if (rank[a] < rank[b]){
                int tmp = a;
                a = b;
                b = tmp;
            }
            parent[b] = a;
            // if (rank[a] == rank[b])
            //     rank[a]++;
            rank[a] += rank[b];
            max1 = Math.max(max1,rank[a]);
            // System.out.println(a+" "+b+" "+rank[a]+" "+rank[b]);
        }
    }

    static int parent1[];
    static int rank1[];

    static int find_set1(int v) {
        if (v == parent1[v])
            return v;
        return find_set1(parent1[v]);
    }

    static void make_set1(int v) {
        parent1[v] = v;
        rank1[v] = 1;
    }

    static void union_sets1(int a, int b) {
        a = find_set1(a);
        b = find_set1(b);
        if (a != b) {
            if (rank1[a] < rank1[b]){
                int tmp = a;
                a = b;
                b = tmp;
            }
            parent1[b] = a;
            // if (rank1[a] == rank1[b])
            //     rank1[a]++;
            rank1[a] += rank1[b];
        }
    }

    static long max1 = 0;

    static int count = 0;
    static int count1 = 0;

    public static void solve(InputReader sc, PrintWriter pw){
        int i, j = 0;
        int t = 1;
        long mod = 998244353;
        // int factors[] = new int[1000001];
        // ArrayList<Integer> ar = new ArrayList<>();
        // sieveOfEratosthenes(1000000, factors, ar);
        // HashSet<Integer> set = new HashSet<>();
        // for(int x:ar){
        //     set.add(x);
        // }
        // int t = sc.nextInt();
        u: while (t-- > 0) {
            long x = sc.nextLong();
            long y = sc.nextLong();
            if(x==y){
                pw.println("YES");
                continue u;
            }
            long tx = 2*x+1;
            while(x%2==0){
                x /= 2;
            }
            char ch1[] = Long.toBinaryString(x).toCharArray();
            char ch2[] = Long.toBinaryString(y).toCharArray();
            x:for(i=0;i<ch2.length;i++){
                for(j=0;j<i;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                for(j=0;j<ch1.length;j++){
                    if(i+j>=ch2.length)
                        continue x;
                    if(ch2[i+j]!=ch1[j])
                        continue x;
                }
                for(j=i+ch1.length;j<ch2.length;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                pw.println("YES");
                continue u;
            }
            for(i=0;i<ch2.length/2;i++){
                char temp = ch2[i];
                ch2[i] = ch2[ch2.length-1-i];
                ch2[ch2.length-1-i] = temp;
            }
            x:for(i=0;i<ch2.length;i++){
                for(j=0;j<i;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                for(j=0;j<ch1.length;j++){
                    if(i+j>=ch2.length)
                        continue x;
                    if(ch2[i+j]!=ch1[j])
                        continue x;
                }
                for(j=i+ch1.length;j<ch2.length;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                pw.println("YES");
                continue u;
            }
            x = tx;
            ch1 = Long.toBinaryString(x).toCharArray();
            ch2 = Long.toBinaryString(y).toCharArray();
            x:for(i=0;i<ch2.length;i++){
                for(j=0;j<i;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                for(j=0;j<ch1.length;j++){
                    if(i+j>=ch2.length)
                        continue x;
                    if(ch2[i+j]!=ch1[j])
                        continue x;
                }
                for(j=i+ch1.length;j<ch2.length;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                pw.println("YES");
                continue u;
            }
            for(i=0;i<ch2.length/2;i++){
                char temp = ch2[i];
                ch2[i] = ch2[ch2.length-1-i];
                ch2[ch2.length-1-i] = temp;
            }
            x:for(i=0;i<ch2.length;i++){
                for(j=0;j<i;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                for(j=0;j<ch1.length;j++){
                    if(i+j>=ch2.length)
                        continue x;
                    if(ch2[i+j]!=ch1[j])
                        continue x;
                }
                for(j=i+ch1.length;j<ch2.length;j++){
                    if(ch2[j]=='0')
                        continue x;
                }
                pw.println("YES");
                continue u;
            }
            pw.println("NO");
        }
    }

    static void KMPSearch(char pat[], char txt[], int pres[]){
        int M = pat.length;
        int N = txt.length;
        int lps[] = new int[M];
        int j = 0;
        computeLPSArray(pat, M, lps);
        int i = 0;
        while (i < N) {
            if (pat[j] == txt[i]) {
                j++;
                i++;
            }
            if (j == M) {
                pres[i-1] = 1;
                j = lps[j - 1];
            }
            else if (i < N && pat[j] != txt[i]) {
                if (j != 0)
                    j = lps[j - 1];
                else
                    i = i + 1;
            }
        }
    }

    static void computeLPSArray(char pat[], int M, int lps[])
    {
        int len = 0;
        int i = 1;
        lps[0] = 0;
        while (i < M) {
            if (pat[i] == pat[len]) {
                len++;
                lps[i] = len;
                i++;
            }
            else
            {
                if (len != 0) {
                    len = lps[len - 1];
                }
                else
                {
                    lps[i] = len;
                    i++;
                }
            }
        }
    }

    static long[][] matrixMult(long a[][], long b[][], long mod){
        int n = a.length;
        int m = a[0].length;
        int p = b[0].length;
        long c[][] = new long[n][p];
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                for(int k=0;k<p;k++){
                    c[i][k] += a[i][j]*b[j][k];
                    c[i][k] %= mod;
                }
            }
        }
        return c;
    }

    static long[][] exp(long mat[][], long b, long mod){
        if(b==0){
            int n = mat.length;
            long res[][] = new long[n][n];
            for(int i=0;i<n;i++){
                res[i][i] = 1;
            }
            return res;
        }
        long half[][] = exp(mat, b/2, mod);
        long res[][] = matrixMult(half, half, mod);
        if(b%2==1){
            res = matrixMult(res, mat, mod);
        }
        return res;
    }

    static void countPrimeFactors(int num, int a[], HashMap<Integer,Integer> pos){
        for(int i=2;i*i<num;i++){
            if(num%i==0){
                int y = pos.get(i);
                while(num%i==0){
                    a[y]++;
                    num/=i;
                }
            }
        }
        if(num>1){
            int y = pos.get(num);
            a[y]++;
        }
    }

    static void assignAnc(ArrayList<Integer> ar[], int depth[], int sz[], int par[][] ,int curr, int parent, int d){
        depth[curr] = d;
        sz[curr] = 1;
        par[curr][0] = parent;
        for(int v:ar[curr]){
            if(parent==v)
                continue;
            assignAnc(ar, depth, sz, par, v, curr, d+1);
            sz[curr] += sz[v];
        }
    }

    static int findLCA(int a, int b, int par[][], int depth[]){
        if(depth[a]>depth[b]){
            a = a^b;
            b = a^b;
            a = a^b;
        }
        int diff = depth[b] - depth[a];
        for(int i=19;i>=0;i--){
            if((diff&(1<<i))>0){
                b = par[b][i];
            }
        }
        if(a==b)
            return a;
        for(int i=19;i>=0;i--){
            if(par[b][i]!=par[a][i]){
                b = par[b][i];
                a = par[a][i];
            }
        }
        return par[a][0];
    }

    static void formArrayForBinaryLifting(int n, int par[][]){
        for(int j=1;j<20;j++){
            for(int i=0;i<n;i++){
                if(par[i][j-1]==-1)
                    continue;
                par[i][j] = par[par[i][j-1]][j-1];
            }
        }
    }

    static long lcm(int a, int b){
        return a*b/gcd(a,b);
    }

    static class Pair1 {
        long a;
        long b;

        Pair1(long a, long b) {
            this.a = a;
            this.b = b;
        }
    }

    static class Pair implements Comparable<Pair> {
        int a;
        int b;
        // int c;

        Pair(int a, int b) {
            this.a = a;
            this.b = b;
            // this.c = c;
        }

        public int compareTo(Pair p) {
            if(a!=p.a)
                return p.a-a;
            return b-p.b;
        }
    }

    static class Pair2 implements Comparable<Pair2> {
        int a;
        int b;
        int c;

        Pair2(int a, int b, int c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }

        public int compareTo(Pair2 p) {
            return a-p.a;
        }
    }

    static boolean isPrime(int n) {
        if (n <= 1)
            return false;
        if (n <= 3)
            return true;
        if (n % 2 == 0 ||  n % 3 == 0)
            return false;
        for (int i = 5; i * i <= n; i = i + 6)
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        return true;
    }

    static long gcd(long a, long b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }

    static long fast_pow(long base, long n, long M) {
        if (n == 0)
            return 1;
        if (n == 1)
            return base % M;
        long halfn = fast_pow(base, n / 2, M);
        if (n % 2 == 0)
            return (halfn * halfn) % M;
        else
            return (((halfn * halfn) % M) * base) % M;
    }

    static long modInverse(long n, long M) {
        return fast_pow(n, M - 2, M);
    }

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

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 9992768);
            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());
        }

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


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

public class MainA {

    public static void main(String[] args) throws IOException {
        new MainA().solve();
    }

    PrintWriter out;
    boolean[] u;
    ArrayList<Integer>[] g;
    int cnt = 0;
    int ind = 0;
    int n;
    int[] a = new int[1000000];
    long MOD = 1000000007;

    void solve() throws IOException{
        Reader in = new Reader("input.txt");
        out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
//		out = new PrintWriter(new FileWriter(new File("output.txt")));

        //int n = in.nextInt();

        int[] r = new int[2000011];

        int qq = in.nextInt();
        int pp = in.nextInt();

        r[1] = 1;

        for (int i = 2; i <= 2000000; i++) {
            r[i] = r[i-1];
            String s = ""+i;
            int ll = 0;
            int rr = s.length()-1;

            boolean ok = true;

            while (ll < rr) {
                if (s.charAt(ll) != s.charAt(rr))
                    ok = false;
                ll++;
                rr--;
            }

            if (ok) {
                r[i]++;
                //System.out.println(s);
            }
        }

        int[] p = new int[2000010];

        for (int i = 2; i <= Math.sqrt(2000010); i++)
            if (p[i] == 0)
                for (int j = i+i; j <= 2000000; j+=i)
                    p[j] = 1;

        int[] pi = new int[2000010];
        pi[1] = 0;

        for (int i = 2; i <= 2000000; i++) {
            pi[i] = pi[i-1];
            if (p[i] == 0) {
                pi[i]++;
                //System.out.println(i);
            }
        }

        int k = 0;

        //System.out.println(pi[109]+" "+r[109]);

        //System.out.println(r[1000]);

        for (int i = 0; i <= 2000000; i++) {
            if (pi[i]*pp <= r[i]*qq)
                k = i;
        }

        //System.out.println(pi[k+1]);

        System.out.println(k);

        out.flush();
        out.close();
    }

    static class Pair implements Comparable<Pair> {

        int a;
        int b;

        public Pair( int a, int b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public int compareTo(Pair o) {

            if (o.a > a) return -1;
            if (o.a < a) return 1;
            if (o.b < b) return 1;
            if (o.b > b) return -1;
            return 0;
        }
    }

    class Reader {

        StringTokenizer token;
        BufferedReader in;

        public Reader(String file) throws IOException {
//	        in = new BufferedReader( new FileReader( file ) );
            in = new BufferedReader( new InputStreamReader( System.in ) );
        }

        public byte nextByte() throws IOException {
            return Byte.parseByte(Next());
        }

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

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

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

        public String nextString() throws IOException {
            return in.readLine();
        }

        private String Next() throws IOException {
            while (token == null || !token.hasMoreTokens()) {
                token = new StringTokenizer(in.readLine());
            }
            return token.nextToken();
        }

    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.StringTokenizer;

public class CodeJ
{
	static class Scanner
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

		public String nextLine()
		{
			try
			{
				return br.readLine();
			}
			catch(Exception e)
			{
				throw(new RuntimeException());
			}
		}

		public String next()
		{
			while(!st.hasMoreTokens())
			{
				String l = nextLine();
				if(l == null)
					return null;
				st = new StringTokenizer(l);
			}
			return st.nextToken();
		}

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

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

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

		public int[] nextIntArray(int n)
		{
			int[] res = new int[n];
			for(int i = 0; i < res.length; i++)
				res[i] = nextInt();
			return res;
		}

		public long[] nextLongArray(int n)
		{
			long[] res = new long[n];
			for(int i = 0; i < res.length; i++)
				res[i] = nextLong();
			return res;
		}

		public double[] nextDoubleArray(int n)
		{
			double[] res = new double[n];
			for(int i = 0; i < res.length; i++)
				res[i] = nextDouble();
			return res;
		}
		public void sortIntArray(int[] array)
		{
			Integer[] vals = new Integer[array.length];
			for(int i = 0; i < array.length; i++)
				vals[i] = array[i];
			Arrays.sort(vals);
			for(int i = 0; i < array.length; i++)
				array[i] = vals[i];
		}

		public void sortLongArray(long[] array)
		{
			Long[] vals = new Long[array.length];
			for(int i = 0; i < array.length; i++)
				vals[i] = array[i];
			Arrays.sort(vals);
			for(int i = 0; i < array.length; i++)
				array[i] = vals[i];
		}

		public void sortDoubleArray(double[] array)
		{
			Double[] vals = new Double[array.length];
			for(int i = 0; i < array.length; i++)
				vals[i] = array[i];
			Arrays.sort(vals);
			for(int i = 0; i < array.length; i++)
				array[i] = vals[i];
		}

		public String[] nextStringArray(int n)
		{
			String[] vals = new String[n];
			for(int i = 0; i < n; i++)
				vals[i] = next();
			return vals;
		}

		Integer nextInteger()
		{
			String s = next();
			if(s == null)
				return null;
			return Integer.parseInt(s);
		}

		int[][] nextIntMatrix(int n, int m)
		{
			int[][] ans = new int[n][];
			for(int i = 0; i < n; i++)
				ans[i] = nextIntArray(m);
			return ans;
		}

		static <T> T fill(T arreglo, int val)
		{
			if(arreglo instanceof Object[])
			{
				Object[] a = (Object[]) arreglo;
				for(Object x : a)
					fill(x, val);
			}
			else if(arreglo instanceof int[])
				Arrays.fill((int[]) arreglo, val);
			else if(arreglo instanceof double[])
				Arrays.fill((double[]) arreglo, val);
			else if(arreglo instanceof long[])
				Arrays.fill((long[]) arreglo, val);
			return arreglo;
		}

		<T> T[] nextObjectArray(Class <T> clazz, int size)
		{
			@SuppressWarnings("unchecked")
			T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
			for(int c = 0; c < 3; c++)
			{
				Constructor <T> constructor;
				try
				{
					if(c == 0)
						constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE);
					else if(c == 1)
						constructor = clazz.getDeclaredConstructor(Scanner.class);
					else
						constructor = clazz.getDeclaredConstructor();
				}
				catch(Exception e)
				{
					continue;
				}
				try
				{
					for(int i = 0; i < result.length; i++)
					{
						if(c == 0)
							result[i] = constructor.newInstance(this, i);
						else if(c == 1)
							result[i] = constructor.newInstance(this);
						else
							result[i] = constructor.newInstance();
					}
				}
				catch(Exception e)
				{
					throw new RuntimeException(e);
				}
				return result;
			}
			throw new RuntimeException("Constructor not found");
		}
	}

	static int factorial(int n)
	{
		if(n == 0) return 1;
		return n * factorial(n - 1);
	}

	static int[] permutar(boolean[] usados, int[] numeros, int n, int k)
	{
		if(n == usados.length)
			return numeros;
		int faltantes = usados.length - n;
		int sigFact = factorial(faltantes - 1);
		for(int i = 0; i < usados.length; i++)
		{
			if(!usados[i])
			{
				if(sigFact >= k)
				{
					usados[i] = true;
					numeros[n] = i;
					return permutar(usados, numeros, n + 1, k);
				}
				else
					k -= sigFact;
			}
		}
		return null;
	}

	static int contarHasta(int n)
	{
		int cuenta = 0;
		for(int i = 1; i < 10; i++)
		{
			int limite = 1 << i;
			for(int j = 0; j < limite; j++)
			{
				char[] val = new char[i];
				for(int k = 0; k < i; k++)
				{
					if((j & (1 << k)) != 0)
						val[k] = '4';
					else
						val[k] = '7';
				}
				if(Integer.parseInt(new String(val)) <= n)
					cuenta++;
			}
		}
		return cuenta;
	}

	static boolean esLucky(int j)
	{
		for(char c : (j + "").toCharArray())
			if(c != '4' && c != '7')
				return false;
		return true;
	}

	public static void main(String[] args)
	{
		Scanner sc = new Scanner();
		int n = sc.nextInt();
		int k = sc.nextInt();
		if(n > 13)
		{
			int total = contarHasta(n - 13);
			int[] vals = permutar(new boolean[13], new int[13], 0, k);
			for(int i = 0; i < 13; i++) vals[i] += n - 12;
			for(int i = 0, j = n - 12; i < 13; i++, j++)
				if(esLucky(vals[i]) && esLucky(j)) total++;
			System.out.println(total);
		}
		else
		{
			if(k > factorial(n))
			{
				System.out.println(-1);
				return;
			}
			int total = 0;
			int[] vals = permutar(new boolean[n], new int[n], 0, k);
			for(int i = 0; i < n; i++) vals[i] += 1;
			for(int i = 0, j = 1; i < n; i++, j++)
				if(esLucky(vals[i]) && esLucky(j)) total++;
			System.out.println(total);
		}
	}
}