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

/**
 * @author Don Li
 */
public class FindACar {

    int N = 30;
    int MOD = (int) 1e9 + 7;

    int a, b, c;

    int[][][][] dp = new int[N + 1][2][2][2];
    int[][][][] cnt = new int[N + 1][2][2][2];

    void solve() {
        int q = in.nextInt();
        while (q-- > 0) {
            int x1 = in.nextInt() - 1, y1 = in.nextInt() - 1, x2 = in.nextInt() - 1, y2 = in.nextInt() - 1, k = in.nextInt() - 1;

            long ans = 0;
            ans = (ans + calc(x2, y2, k)) % MOD;
            ans = (ans - calc(x1 - 1, y2, k) + MOD) % MOD;
            ans = (ans - calc(x2, y1 - 1, k) + MOD) % MOD;
            ans = (ans + calc(x1 - 1, y1 - 1, k)) % MOD;

            out.println(ans);
        }
    }

    int calc(int x, int y, int k) {
        if (x < 0 || y < 0) return 0;

        for (int i = 0; i <= N; i++)
            for (int j = 0; j < 2; j++)
                for (int u = 0; u < 2; u++)
                    for (int v = 0; v < 2; v++)
                        dp[i][j][u][v] = cnt[i][j][u][v] = -1;

        a = x;
        b = y;
        c = k;
        return dfs1(N, 1, 1, 1);
    }

    int dfs1(int i, int ea, int eb, int ec) {
        if (i < 0) return 1;
        if (dp[i][ea][eb][ec] >= 0) return dp[i][ea][eb][ec];

        int bit_a = (a >> i) & 1;
        int bit_b = (b >> i) & 1;
        int bit_c = (c >> i) & 1;

        long res = 0;

        int nec = ec == 1 && bit_c == 0 ? 1 : 0;
        int nea = ea == 1 && bit_a == 0 ? 1 : 0;
        int neb = eb == 1 && bit_b == 0 ? 1 : 0;
        res = (res + dfs1(i - 1, nea, neb, nec)) % MOD;

        if ((eb == 0 || bit_b == 1) && (ec == 0 || bit_c == 1)) {
            nec = ec == 1 && bit_c == 1 ? 1 : 0;
            nea = ea == 1 && bit_a == 0 ? 1 : 0;
            neb = eb == 1 && bit_b == 1 ? 1 : 0;
            res = (res + (1L << i) * dfs2(i - 1, nea, neb, nec) % MOD + dfs1(i - 1, nea, neb, nec)) % MOD;
        }

        if ((ea == 0 || bit_a == 1) && (ec == 0 || bit_c == 1)) {
            nec = ec == 1 && bit_c == 1 ? 1 : 0;
            nea = ea == 1 && bit_a == 1 ? 1 : 0;
            neb = eb == 1 && bit_b == 0 ? 1 : 0;
            res = (res + (1L << i) * dfs2(i - 1, nea, neb, nec) % MOD + dfs1(i - 1, nea, neb, nec)) % MOD;
        }

        if ((ea == 0 || bit_a == 1) && (eb == 0 || bit_b == 1)) {
            nec = ec == 1 && bit_c == 0 ? 1 : 0;
            nea = ea == 1 && bit_a == 1 ? 1 : 0;
            neb = eb == 1 && bit_b == 1 ? 1 : 0;
            res = (res + dfs1(i - 1, nea, neb, nec)) % MOD;
        }

        return (int) res;
    }

    int dfs2(int i, int ea, int eb, int ec) {
        if (i < 0) return 1;
        if (cnt[i][ea][eb][ec] >= 0) return cnt[i][ea][eb][ec];

        int bit_a = (a >> i) & 1;
        int bit_b = (b >> i) & 1;
        int bit_c = (c >> i) & 1;

        long res = 0;

        int nec = ec == 1 && bit_c == 0 ? 1 : 0;
        int nea = ea == 1 && bit_a == 0 ? 1 : 0;
        int neb = eb == 1 && bit_b == 0 ? 1 : 0;
        res = (res + dfs2(i - 1, nea, neb, nec)) % MOD;

        if ((eb == 0 || bit_b == 1) && (ec == 0 || bit_c == 1)) {
            nec = ec == 1 && bit_c == 1 ? 1 : 0;
            nea = ea == 1 && bit_a == 0 ? 1 : 0;
            neb = eb == 1 && bit_b == 1 ? 1 : 0;
            res = (res + dfs2(i - 1, nea, neb, nec)) % MOD;
        }

        if ((ea == 0 || bit_a == 1) && (ec == 0 || bit_c == 1)) {
            nec = ec == 1 && bit_c == 1 ? 1 : 0;
            nea = ea == 1 && bit_a == 1 ? 1 : 0;
            neb = eb == 1 && bit_b == 0 ? 1 : 0;
            res = (res + dfs2(i - 1, nea, neb, nec)) % MOD;
        }

        if ((ea == 0 || bit_a == 1) && (eb == 0 || bit_b == 1)) {
            nec = ec == 1 && bit_c == 0 ? 1 : 0;
            nea = ea == 1 && bit_a == 1 ? 1 : 0;
            neb = eb == 1 && bit_b == 1 ? 1 : 0;
            res = (res + dfs2(i - 1, nea, neb, nec)) % MOD;
        }

        return (int) res;
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new FindACar().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

        public String nextToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;

public class Main {

	private static final String NO = "NO";
	private static final String YES = "YES";
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	private static final long MOD = 1000000007;

	void solve() {
		int T = 1;
		for (int i = 0; i < T; i++)
			solve(i);
	}

	long p[];

	void solve(int T) {
		int n = ni();
		p = new long[64];
		p[0] = 1;
		for (int i = 1; i < 60; i++)
			p[i] = p[i - 1] * 2;

		for (int i = 0; i < n; i++) {
			int a[] = na(5);
			long ans = work(a[2], a[3], a[4], 0) - work(a[0] - 1, a[3], a[4], 0) - work(a[2], a[1] - 1, a[4], 0)
					+ work(a[0] - 1, a[1] - 1, a[4], 0);
			out.println((ans + MOD) % MOD);
		}
	}

	long work(long x, long y, long k, long lazy) {
		if (x <= 0 || y <= 0)
			return 0;
		if (k <= 0)
			return 0;
		if (x > y) {
			long tmp = x;
			x = y;
			y = tmp;
		}
		int t = 0;
		while (p[t] <= y)
			t++;

		long ans;
		if (y == p[t - 1]) {
			long tmpa, tmpb;
			if (p[t - 1] < k)// all numbers is within [1..k], count them all
			{
				tmpa = p[t - 1];
				tmpa = tmpa * (tmpa + 1) / 2;
				tmpa %= MOD;
				tmpa *= x;
				tmpa %= MOD;
				tmpb = (lazy * y) % MOD;
				tmpb *= x;
				tmpb %= MOD;
				ans = (tmpa + tmpb) % MOD;
			} else// p[t-1]>=k only less or equal to k is needed
			{
				tmpa = k;
				tmpa = tmpa * (tmpa + 1) / 2;
				tmpa %= MOD;
				tmpa *= x;
				tmpa %= MOD;
				tmpb = (lazy * k) % MOD;
				tmpb *= x;
				tmpb %= MOD;
				ans = (tmpa + tmpb) % MOD;
			}
		} else// y > p[t-1]
		{
			if (x < p[t - 1]) {
				ans = work(x, p[t - 1], k, lazy);
				ans = (ans + work(x, y - p[t - 1], k - p[t - 1], lazy + p[t - 1])) % MOD;
			} else {
				ans = work(p[t - 1], p[t - 1], k, lazy);
				ans = (ans + work(x - p[t - 1], p[t - 1], k - p[t - 1], lazy + p[t - 1])) % MOD;
				ans = (ans + work(p[t - 1], y - p[t - 1], k - p[t - 1], lazy + p[t - 1])) % MOD;
				ans = (ans + work(x - p[t - 1], y - p[t - 1], k, lazy)) % MOD;
			}
		}
//		tr(x, y, k, lazy, ans);

		return ans;
	}

	// a^b
	long power(long a, long b) {
		long x = 1, y = a;
		while (b > 0) {
			if (b % 2 != 0) {
				x = (x * y) % MOD;
			}
			y = (y * y) % MOD;
			b /= 2;
		}
		return x % MOD;
	}

	private long gcd(long a, long b) {
		while (a != 0) {
			long tmp = b % a;
			b = a;
			a = tmp;
		}
		return b;
	}

	void run() throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		if (!INPUT.isEmpty())
			tr(System.currentTimeMillis() - s + "ms");
	}

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

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;
	private boolean vis[];

	private int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd() {
		return Double.parseDouble(ns());
	}

	private char nc() {
		return (char) skip();
	}

	private String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
									// ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n) {
			if (!(isSpaceChar(b)))
				buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private List<Integer> na2(int n) {
		List<Integer> a = new ArrayList<Integer>();
		for (int i = 0; i < n; i++)
			a.add(ni());
		return a;
	}

	private int[][] na(int n, int m) {
		int[][] a = new int[n][];
		for (int i = 0; i < n; i++)
			a[i] = na(m);
		return a;
	}

	private int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long[] nl(int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nl();
		return a;
	}

	private long[][] nl(int n, int m) {
		long[][] a = new long[n][];
		for (int i = 0; i < n; i++)
			a[i] = nl(m);
		return a;
	}

	private long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private static void tr(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}

	public class Pair<K, V> {

		/**
		 * Key of this Pair.
		 */
		private K key;

		/**
		 * Gets the key for this pair.
		 *
		 * @return key for this pair
		 */
		public K getKey() {
			return key;
		}

		/**
		 * Value of this this Pair.
		 */
		private V value;

		/**
		 * Gets the value for this pair.
		 *
		 * @return value for this pair
		 */
		public V getValue() {
			return value;
		}

		/**
		 * Creates a new pair
		 *
		 * @param key   The key for this pair
		 * @param value The value to use for this pair
		 */
		public Pair(K key, V value) {
			this.key = key;
			this.value = value;
		}

		/**
		 *

		 * String representation of this Pair.
		 *

		 *
		 *

		 * The default name/value delimiter '=' is always used.
		 *

		 *
		 * @return String representation of this Pair
		 */
		@Override
		public String toString() {
			return key + "=" + value;
		}

		/**
		 *

		 * Generate a hash code for this Pair.
		 *

		 *
		 *

		 * The hash code is calculated using both the name and the value of the
		 * Pair.
		 *

		 *
		 * @return hash code for this Pair
		 */
		@Override
		public int hashCode() {
			// name's hashCode is multiplied by an arbitrary prime number (13)
			// in order to make sure there is a difference in the hashCode between
			// these two parameters:
			// name: a value: aa
			// name: aa value: a
			return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
		}

		/**
		 *

		 * Test this Pair for equality with another Object.
		 *

		 *
		 *

		 * If the Object to be tested is not a Pair or is
		 * null, then this method returns false.
		 *

		 *
		 *

		 * Two Pairs are considered equal if and only if both the names and
		 * values are equal.
		 *

		 *
		 * @param o the Object to test for equality with this
		 *          Pair
		 * @return true if the given Object is equal to this
		 *         Pair else false
		 */
		@Override
		public boolean equals(Object o) {
			if (this == o)
				return true;
			if (o instanceof Pair) {
				Pair pair = (Pair) o;
				if (key != null ? !key.equals(pair.key) : pair.key != null)
					return false;
				if (value != null ? !value.equals(pair.value) : pair.value != null)
					return false;
				return true;
			}
			return false;
		}
	}

}


import java.util.Scanner;

public class AtoB {

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		int a = in.nextInt(), b = in.nextInt();
		in.close();

		int[] k = new int[b + 1];
		k[a] = 1;

		int i = a + 1;
		while(i < b + 1){
			k[i] += f(i % 10 - 1) * k[i / 10];
			k[i] += (1 - i % 2) * k[i / 2];
			i++;
		}

		if(k[b] == 0){
			System.out.println("NO");
			return;
		}else System.out.println("YES");

		String ans = "";
		ans += b;
		int len = 1;
		i--;
		while(i > a){
			if(i % 10 == 1){
				ans = i / 10 + " " + ans;
				i /= 10;
				len++;
			}
			if(i % 2 == 0){
				ans = i / 2 + " " + ans;
				i /= 2;
				len++;
			}
		}

		System.out.println(len);
		System.out.println(ans);

	}

	public static int f(int x){
		return 1 / (x * x + 1);
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class C {
  public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out = new PrintWriter(System.out);
    long card = Long.parseLong(in.readLine());
    long ans = 0;
    long floor = 1;
    long base = 0;
    while (true) {
      long c = card - 2 * floor;
      if (c < 0)
        break;
      if (c % 3 == 0 && c / 3 >= base)
        ans++;
      base += floor;
      floor++;
    }
    out.println(ans);
    out.close();
    in.close();
  }
}


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

public class D {
  public static void main(String[] args){
    int n, r, v;
    Scanner sc = new Scanner(System.in);
    n = sc.nextInt();
    r = sc.nextInt();
    v = sc.nextInt();
    for(int i = 0; i<n; i++){
      solve(sc, r, v);
    }
  }

  public static void solve(Scanner sc, int r, int v){
    /*
      int s, f
      d = f-s
      p = 2 * pi * r
      rounds = Math.floor( d/p)
      left = d - rounds * p
      we have: alpha + sin(alpha) = left/ (2*r)
    */
    int s = sc.nextInt();
    int f = sc.nextInt();
    int d = f-s;
    double p = 2 * Math.PI * r;
    double rounds = Math.floor(d / p );
    //double rr = (d - p * rounds) / (2 * r);
    double rr = d - p * rounds;
    double r2 = 2 * r;
    double alpha = rr/r2;
    double threshold = 0.0000001;

    double diff = Math.abs((alpha + Math.sin(alpha))* r2 - rr);
    /*
    double diff = Math.abs(alpha + Math.sin(alpha) - rr);
    while(diff > threshold){
      alpha = rr - Math.sin(alpha);
      diff = Math.abs(alpha+ Math.sin(alpha) - rr);
    }
    */
    double low = 0;
    double high= rr/r2;
    alpha = (low + high)/  2;
    rr /= r2;
    diff = ((alpha + Math.sin(alpha))- rr);
    /*
    while(diff > threshold){
      alpha = rr/r2 - Math.sin(alpha);
      diff = Math.abs((alpha + Math.sin(alpha))* r2 - rr);
    }
    */
    while(Math.abs(diff)*r2 > threshold){
      alpha = (low + high) / 2;
      diff = ((alpha + Math.sin(alpha)) - rr);
      if (diff > 0) high = alpha;
      else low = alpha;
    }
    double travelDistance = d - 2 * r * Math.sin(alpha);
    System.out.println(travelDistance / v);
  }
}


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

public class Solution{
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int k = scan.nextInt();
		String box = scan.next();
		int src = -1;
		int dest = -1;
		for (int i = 0; i < box.length(); i++){
			if (src != -1 && dest != -1)
				break;
			if(box.charAt(i) == 'G'){
				src = i;
			}
			if (box.charAt(i) == 'T'){
				dest = i;
			}
		}
		Queue<Integer> queue = new LinkedList<>();
		queue.add(src);
		boolean found = true;
		while(!queue.isEmpty()){
			Integer curr = queue.remove();
			if (curr == dest){
				found = true;
				break;
			}
			if (curr - k > 0)
				queue.add(curr - k);
			if (curr + k > 0)
				queue.add(curr + k);
		}
		if (found){
			System.out.println("YES");
		}
		else{
			System.out.println("NO");
		}
	}
}


package codeforces;

import java.util.Scanner;
import java.util.Stack;

public class trials {

	public static void main(String[] args) {

		Scanner sc= new Scanner(System.in);
		int []z = new int [4];

		for(int i=0;i<4;i++) {
			z[i]=sc.nextInt();

			}

	System.out.println(z[0]==z[3]&&(z[2]==0||z[0]>0)?"1":"0");

}
}


//import java.util.*;
public class EpicGame{
	public static void main(String[]args){
		//Scanner in = new Scanner(System.in);
		//int a = in.nextInt();
		//int b = in.nextInt();
		//int n = in.nextInt();
		int t1 = 8;
		int t2 = 12;
		System.out.println(gcd(t1, t2));
	}

	public static int gcd(int i1, int i2){
		if(i1==0&&i2!=0) return i2;
		if(i2==0&&i1!=0) return i1;

		for(int i=i1; i>0; i--){
			while(i>=1){
				if(i1%i==0&&i2%i==0) return i;
			}
		}
		return 0;
	}
}


import java.util.Scanner;
public class RaceAgainstTime {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int h=in.nextInt()*5,m=in.nextInt(),s=in.nextInt(),i=in.nextInt()*5,f=in.nextInt()*5,count=0;
		boolean inc=true;

		while(i!=f && count<2){
			if(inc){
				i++;
				if(i==60)
					i=0;
			}
			else
				i--;
				if(i==0)
					i=60;
			if(i==h || i==m || i==s){
				inc = !inc;
				count++;
			}
		}

		System.out.println(count<2 ? "YES":"NO");

	}
}


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt(),m=sc.nextInt();
        System.out.print((Math.max(n,m)-1)+" "+Math.min(n,m));

    }
}


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Task245B {

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

	static class Solution {

		static long combinations(int n, int k) {
			long retVal = 1;
			for (int i = 0; i < k;) {
				retVal *= n - i;
				i++;
				retVal /= i;
			}
			return retVal;
		}

		public static void main(InputStream is, OutputStream os)
				throws NumberFormatException, IOException {
			PrintWriter pw = new PrintWriter(os);
			Scanner s = new Scanner(is);

			String input = s.next();
			if (input.startsWith("http")) {
				pw.write("http://");
				input = input.substring(4);
			} else {
				pw.write("ftp://");
				input = input.substring(3);
			}

			int domainEnd = input.indexOf("ru");

			pw.print(input.substring(0, domainEnd));
			pw.print(".ru");
			domainEnd += 2;
			if (domainEnd < input.length()) {
				pw.print("/" + input.substring(domainEnd));
			}
			pw.println();
			pw.flush();
			s.close();
		}
	}

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner (System.in);
        String array;
        float x,y;
        Main test=new Main();
        line inst=test.new line();
        x= scanner.nextFloat();
        y= scanner.nextFloat();
        array=scanner.next();
        ArrayList<line> liness;
        liness=go(array);

        if(ifclosedpath(liness)==1)
              if( firstpath(x,y,liness)==1)
                {System.out.println("yes");
                return;
                }
            else
                {System.out.println("No");
                return;
                }

                if(firstpath(x,y,liness)==1)
                    System.out.println("yes");
                else
                    if(checkpoint(x,y,liness)>=0)
                        System.out.println("yes");

            else
                System.out.println("No");

    }

static ArrayList<line> go(String array)
{
    int n=0;
   float x=0;
    float y=0;
    ArrayList<line> lines=new ArrayList<line>() ;
    Main test=new Main();
    line inst=test.new line();

      int l=array.length();

    while(n<l)
    {

        if(array.charAt(n)=='U')
        y=y+1;
        if(array.charAt(n)=='D')
        y=y-1;
        if(array.charAt(n)=='L')
        x=x-1;
        if(array.charAt(n)=='R')
        x=x+1;

        inst=new test.new line();
        inst.setX1(x);
        inst.setY1(y);
        lines.add(n,inst);

       n=n+1;

   }

    n=0;

    while(n<l)
    {

        if(array.charAt(n)=='U')
        y=y+1;
        if(array.charAt(n)=='D')
        y=y-1;
        if(array.charAt(n)=='L')
        x=x-1;
        if(array.charAt(n)=='R')
        x=x+1;

        inst=test.new line();
        inst=lines.get(n);

        inst.setX2(x);
        inst.setY2(y);

        lines.set(n, inst);

        n++;

    }

    for(int counter=0;counter<lines.size();counter++)
    {

        inst=test.new line();
        inst=lines.get(counter);
        inst.makeline();
        lines.set(counter, inst);

    }
    return lines;

}

static int firstpath(float x,float y,ArrayList <line> lines)
{
    Main test=new Main();
        line inst=test.new line();

    int l=lines.size();
    for (int counter=0;counter<l;counter++)
    {

        inst=test.new line();
        inst=lines.get(counter);
        if(x==inst.x1 && y==inst.y1 )
        return 1;

    }
    return 0;

}

static int checkpoint(float x,float y,ArrayList<line> lines)
{
    Main test=new Main();
        line inst=test.new line();

    float r;
    int flag=0;
    int counter;
    if(x==0 && y==0)
    return 0;

    else

    {

for(counter=0;counter<lines.size();counter++)
  {

    inst=test.new line();
    inst=lines.get(counter);
             if(inst.d=='v')
             {

                 if(x==inst.c)
                 {
                     flag++;
                     break;

                 }
             }
             else
                 if(inst.d=='h')
             {

                     if(y==inst.c)
                 {
                     flag++;
                     break;

                 }
             }
             else

      {

        r=inst.m*x;
        r=r+inst.c;

        if(y==r)
        {

            flag++;
            break;

        }

      }

}
    if(flag>0)
    return counter+1;
    else
    return -1;
    }

}

static int ifclosedpath(ArrayList <line> lines)
{

    if(lines.get(0).getX1()==lines.get(0).getX2() && lines.get(0).getY1()==lines.get(0).getY2() )
    return 1;
    else
        return 0;
}

public class line
{
    public float x1,x2,y1,y2,m,c;
    public char d;

    public void setX1(float x1) {
        this.x1 = x1;
    }

    public void setX2(float x2) {
        this.x2 = x2;
    }

    public void setY1(float y1) {
        this.y1 = y1;
    }

    public float getX2() {
        return x2;
    }

    public float getY2() {
        return y2;
    }

    public float getY1() {
        return y1;
    }

    public void setY2(float y2) {
        this.y2 = y2;
    }

    public float getX1() {
        return x1;
    }

    void makeline()
    {

        if(this.x1==this.x2)
        {
            this.d='v';
            this.c=this.x2;

        }
        else
            if(this.y1==this.y2)
            {
                this.d='h';
                this.c=this.y1;
            }
            else
            {
                this.d='n';
                this.m=(this.y2-this.y1)/(this.x2-this.x1);
                this.c=this.y1-(this.m*this.x1);

            }

    }

}

}


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

public class Contest190 {

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

    long a, b;
    long x = 0, y = 0;

    void step(char c) {
        switch(c) {
            case 'U': ++y; break;
            case 'D': --y; break;
            case 'L': --x; break;
            case 'R': ++x; break;
        }
    }

    boolean walk_path(String s) {
        for(int i = 0; i < s.length(); ++i) {
            if(x == a && y == b)
                return true;
            step(s.charAt(i));
        }
        return x == a && y == b;
    }

    int sign(int n) {
        return n < 0 ? -1 : (n == 0 ? 0 : 1);
    }

    void solve() throws IOException {
        a = nextInt();
        b = nextInt();
        String s = nextToken();
        if(walk_path(s)) {
            out.println("Yes");
            return;
        }
        if(x == 0 && y == 0) {
            out.println("No");
            return;
        }

        long steps = Integer.MAX_VALUE;
        if(x != 0 && && a / x != 0)
            steps = Math.max(steps, Math.abs(a / x));
        if(y != 0 && b / y != 0)
            steps = Math.max(steps, Math.abs(b / y));

        if(steps != Integer.MAX_VALUE) {
            x *= steps;
            y *= steps;
        }

        for(int i = 0; i < 500; ++i)
            if(walk_path(s)) {
                out.println("Yes");
                return;
            }
        out.println("No");
    }

    BufferedReader br;
    StringTokenizer st;
    PrintWriter out;

    public String nextToken() throws IOException {
        while(st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(br.readLine());
        }

        return st.nextToken();
    }

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

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

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

    void run() throws IOException {
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;

        br = new BufferedReader( new InputStreamReader( oj ? System.in : new FileInputStream("input.txt")));
        out = new PrintWriter( oj ? System.out : new FileOutputStream("output.txt"));

        solve();

        out.close();
    }

}


import java.io.*;
import java.util.*;
public class d2prac implements Runnable
{
    private boolean console=false;

    public void solve()
    {
    	int i;
    	int n=in.ni();
    	long m=1000000007;
    	long ans=0;
    	long fact[]=new long[n+1];
    	if(n==3)
    	{
    		out.println(2);
    		continue;
    	}
    	fact[4]=8;
    	for(i=5;i<=n;i++)
    		fact[i]=((fact[i-1])*2)%m;
    	long sum=1;
    	for(i=1;i<=n;i++)
    		sum=(sum*i)%m;
    	ans = ((sum - fact[n])%m)+m;
    	out.println(ans%m);
    }
    @Override
    public void run() {
        try {  init();  }
        catch (FileNotFoundException e) {  e.printStackTrace();   }

        int t= 1;

        while (t-->0) {
            solve();
            out.flush(); }
    }
    private FastInput in;    private PrintWriter out;
    public static void main(String[] args) throws Exception {	 new d2prac().run();	 }

    private void init() throws FileNotFoundException {
        InputStream inputStream = System.in; 	 OutputStream outputStream = System.out;
        try {  if (!console && System.getProperty("user.name").equals("sachan")) {
                outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt");
                inputStream = new FileInputStream("/home/sachan/Desktop/input.txt");   	}
        }	catch (Exception ignored) {	}
        out = new PrintWriter(outputStream); 	 in = new FastInput(inputStream);
    }
    static class FastInput { InputStream obj;
    	public FastInput(InputStream obj) {	this.obj = obj;	}
        byte inbuffer[] = new byte[1024];  int lenbuffer = 0, ptrbuffer = 0;
        int readByte() { if (lenbuffer == -1) throw new InputMismatchException();
            if (ptrbuffer >= lenbuffer) { ptrbuffer = 0;
                try { lenbuffer = obj.read(inbuffer);  }
                catch (IOException e) { throw new InputMismatchException(); } }
            if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; }

        String ns() { int b = skip();StringBuilder sb = new StringBuilder();
            while (!(isSpaceChar(b)))	  { sb.appendCodePoint(b);b = readByte(); }return sb.toString();}

        int ni() { int num = 0, b;boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') { minus = true;b = readByte(); }
            while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else {
                    return minus ? -num : num; }b = readByte(); }}

        long nl() { long num = 0;int b;boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') { minus = true;b = readByte(); }
            while (true) { if (b >= '0' && b <= '9') { num = num * 10L + (b - '0'); } else {
                    return minus ? -num : num; }b = readByte(); } }

        boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); }
        int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; }
        float nf() {return Float.parseFloat(ns());}
        double nd() {return Double.parseDouble(ns());}
        char nc() {return (char) skip();}
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class BoryaAndHanabi {
    private BoryaAndHanabi() throws IOException {
        BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
        String h = rd.readLine();
        int n = Integer.parseInt(h);
        h = rd.readLine();
        String[] cards = h.split("\\s+");
        boolean[][] cardExists = new boolean[5][5];
        int[] colorToIndex = new int['Z'];
        colorToIndex['R'] = 0;
        colorToIndex['G'] = 1;
        colorToIndex['B'] = 2;
        colorToIndex['Y'] = 3;
        colorToIndex['W'] = 4;
        for(String c: cards) {
            cardExists[colorToIndex[c.charAt(0)]][c.charAt(1)-'0'] = true;
        }
        int minHints = 10;
        for(int i=0;i<(1<<10);i++) {
            boolean hintsOk = true;
            boolean singleUsed = false;
            for(int j=0;hintsOk && j<5;j++) {
                for(int k=0;hintsOk && k<5;k++) {
                    if(cardExists[j][k]) {
                        boolean colorHint = chint(i, j);
                        boolean digitHint = dhint(i, k);
                        if(!colorHint && !digitHint) {
                            if(singleUsed) {
                                hintsOk = false;
                                break;
                            } else {
                                singleUsed = true;
                            }
                        } else if(colorHint && !digitHint) {
                            for(int m=0;m<5;m++) {
                                if(m != k && cardExists[j][m]) {
                                    if(!dhint(i, m)) {
                                        hintsOk = false;
                                        break;
                                    }
                                }
                            }
                        } else if(!colorHint && digitHint) {
                            for(int m=0;m<5;m++) {
                                if(m != j && cardExists[m][k]) {
                                    if(!chint(i, m)) {
                                        hintsOk = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(hintsOk) {
                int hints = new BigInteger(i+"").bitCount();
                minHints = Math.min(minHints, hints);
            }
        }
        out(minHints);
    }

    private boolean chint(int i, int x) {
        return (i & (1<<x)) > 0;
    }

    private boolean dhint(int i, int x) {
        return (i & (1<<(x+5))) > 0;
    }

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

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


import java.util.Scanner;
/*
 * !!!!!!!!!!!!!!!!!!!!!!!!!
 * !!!!!!ACTUALLY PrC!!!!!!!
 * !!!!!!!!!!!!!!!!!!!!!!!1!
 */
public class PrD {

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

		scan.nextLine();

		boolean cards[][] = new boolean[10][10];

		scan.nextLine();
		String s = scan.nextLine();

		s = s.replaceAll("\\s+", "");
		char c;
		int x;
		for(int i = 0; i < s.length(); i+=2){
			c = s.charAt(i);
			x = Integer.parseInt(String.valueOf(s.charAt(i+1)))-1;
			switch (c){
				case 'R':	cards[0][x] = true;
							break;
				case 'G':	cards[1][x] = true;
							break;
				case 'B':	cards[2][x] = true;
							break;
				case 'Y':	cards[3][x] = true;
							break;
				case 'W':	cards[4][x] = true;
							break;
			}
		}
		int ans = 0;
		int nums = 0, cols = 0;
		for(int i = 0; i < 5; i++){
			for(int j = 0; j < 5; j++){
				if(cards[i][j])
					nums++;

				if(cards[j][i] && i != j)
					cols++;
			}
			if(nums > 0){
				ans += nums-1;
				nums = 0;
			}
			if(cols > 0){
				ans += cols-1;
				cols = 0;
			}
		}
		System.out.println(ans);
	}
}


import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.io.*;
import java.math.*;import static java.lang.Math.*;
import stimport static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.io.*;
import java.math.*;
import java.util.*;

public class CardGame {

    public static void main(String[] args) throws Exception {
        String trump = next();
        String a = next(), b = next();
        String order = "6789TJQKA";
        if ((a.charAt(1) == b.charAt(1) && order.indexOf(a.charAt(0)) > order.indexOf(b.charAt(0))) || (a.charAt(1) == trump.charAt(0) && b.charAt(1) != trump.charAt(0))) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
    }

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

    static void initFileIO(boolean large) throws Exception {
        System.setIn(new FileInputStream("CardGame-" + (large ? "large" : "small") + ".in"));
        System.setOut(new PrintStream("output"));
    }

    static String next() throws Exception {
        while (!st.hasMoreTokens()) {
            String s = in.readLine();
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

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

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

    static double nextDouble() throws Exception {
        return Double.parseDouble(next());
    }
}
atic java.util.Arrays.*;
import static java.util.Collections.*;
import java.io.*;
import java.math.*;
import java.util.*;

public class CardGame {

    public static void main(String[] args) throws Exception {
        String trump = next();
        String a = next(), b = next();
        String order = "6789TJQKA";
        if ((a.charAt(1) == b.charAt(1) && order.indexOf(a.charAt(0)) > order.indexOf(b.charAt(0))) || (a.charAt(1) == trump.charAt(0) && b.charAt(1) != trump.charAt(0))) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
    }

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

    static void initFileIO(boolean large) throws Exception {
        System.setIn(new FileInputStream("CardGame-" + (large ? "large" : "small") + ".in"));
        System.setOut(new PrintStream("output"));
    }

    static String next() throws Exception {
        while (!st.hasMoreTokens()) {
            String s = in.readLine();
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

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

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

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

import java.util.*;

public class CardGame {

    public static void main(String[] args) throws Exception {
        String trump = next();
        String a = next(), b = next();
        String order = "6789TJQKA";
        if (a.charAt(1) == b.charAt(1) || order.indexOf(a.charAt(0)) > order.indexOf(b.charAt(0)) || (a.charAt(1) == trump.charAt(0) && b.charAt(1) != trump.charAt(0))) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
    }

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

    static void initFileIO(boolean large) throws Exception {
        System.setIn(new FileInputStream("CardGame-" + (large ? "large" : "small") + ".in"));
        System.setOut(new PrintStream("output"));
    }

    static String next() throws Exception {
        while (!st.hasMoreTokens()) {
            String s = in.readLine();
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

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

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

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


import java.util.*;

public class Main {

	// global
	static long fact[];
	static long inverse[];
	static int n;
	static int mod;

	static long pow(long a,int n) {
	    long res=1;
	    while (n>0) {
	        if ((n-n/2*2)==1) {
	            res=res*a%mod;
	        }
	        a=a*a%mod;
	        n>>=1;
	    }
	    return res;
	}

	static long modinv(long n) {
	    return pow(n, mod-2);
	}

	static long comb(int n,int k){
	    if(n<0 || k<0 || n<k)return 0;
	    return fact[n]*(inverse[k]*inverse[n-k]%mod) %mod;
	}

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

		// main method
		fact=new long[200000];
		fact[0]=1;
		inverse=new long[200000];
		inverse[0]=1;
		for(int i=1;i<200000;i++){
		    fact[i]=(fact[i-1]*(long)i)%mod;
		    inverse[i]=modinv(fact[i]);
		}

		long ans = 0L;
		for (int i=1;i<=n;i++) {
			// ans = (ans + (((((n-(i-1))*fact[n])%mod*(n-1))%mod*fact[i])%mod*fact[n-i])%mod*modinv(fact[n])%mod)%mod;
			ans = (ans + (((((n-(i-1)))%mod*(n-(i-1)))%mod*fact[i])%mod*fact[n-i])%mod)%mod;
		}
		System.out.println(ans);
	}
}


package ff;

import java.util.Scanner;

public class ZEROS {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		int y = sc.nextInt();

		int winX = 0;
		int draw = 0;
		int winY = 0;

		for (int i = 1; i <= 6; i++) {
			if (Math.abs(i - x) < Math.abs(i - y))
				// System.out.println(i);
				winX++;

			else if (Math.abs(i - x) > Math.abs(i - y))
				winY++;
			else
				draw++;
		}
		System.out.println(winX + " " + draw + " " + winY);
	}
}


import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.List;
 import java.util.*;
 public class realfast implements Runnable
  {
    private static final int INF = (int) 1e9;
    long in= (long)Math.pow(10,9)+7;
    long fac[]= new long[3000];
    public  void solve() throws IOException
    {
         long m = in;

       int x = readInt();
       int y = readInt();

       if((y%x)!=0)
        out.println(0);
       else
       {
            int len =y/x;

            int root = (int)Math.pow(len,0.5);
            ArrayList<Integer> arr = new ArrayList<>();
            for(int i =1;i<=root;i++)
            {
                if(len%i==0)
                {
                    int j = len/i;
                    arr.add(i);
                    if(j!=i)
                        arr.add(j);
                }
            }
            Collections.sort(arr);
            long dp[]= new long[arr.size()];
            dp[arr.size()-1]=1;
            for(int i=arr.size()-2;i>=0;i--)
            {
                int yo = arr.get(i);
                dp[i]= pow(2,len/yo-1,in);
                for(int j=i+1;j<arr.size();j++)
                {
                    int sal = arr.get(j);
                    if(sal%yo==0)
                    dp[i]= (dp[i]%in-dp[j]%in+in)%in;
                }
            }
            out.println(dp[0]);
       }

    }
    public int gcd(int a , int b )
    {
      if(a<b)
      {
        int t =a;
        a=b;
        b=t;
      }
      if(a%b==0)
        return b ;
      return gcd(b,a%b);
    }
    public long pow(long n , long p,long m)
    {
         if(p==0)
            return 1;
        long val = pow(n,p/2,m);;
        val= (val*val)%m;
        if(p%2==0)
            return val;
        else
            return (val*n)%m;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static void main(String[] args) {
        new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
    }

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    private BufferedReader reader;
    private StringTokenizer tokenizer;
    private PrintWriter out;

    @Override
    public void run() {
        try {
            if (ONLINE_JUDGE || !new File("input.txt").exists()) {
                reader = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                reader = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            }
            solve();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // nothing
            }
            out.close();
        }
    }

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

    @SuppressWarnings("unused")
    private int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    @SuppressWarnings("unused")
    private long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    @SuppressWarnings("unused")
    private double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }
}
class edge implements Comparable<edge>{
    int val ;
    int color;

    edge(int u, int v)
    {
       this.val=u;
       this.color=v;
    }
    public int compareTo(edge e)
    {
        return this.val-e.val;
    }
}import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.List;
 import java.util.*;
  class realfast implements Runnable
  {
    private static final int INF = (int) 1e9;
    long in= (long)Math.pow(10,9)+7;
    long fac[]= new long[3000];
    public  void solve() throws IOException
    {
         long m = in;

       int x = readInt();
       int y = readInt();

       if((y%x)!=0)
        out.println(0);
       else
       {
            int len =y/x;

            int root = (int)Math.pow(len,0.5);
            ArrayList<Integer> arr = new ArrayList<>();
            for(int i =1;i<=root;i++)
            {
                if(len%i==0)
                {
                    int j = len/i;
                    arr.add(i);
                    if(j!=i)
                        arr.add(j);
                }
            }
            Collections.sort(arr);
            long dp[]= new long[arr.size()];
            dp[arr.size()-1]=1;
            for(int i=arr.size()-2;i>=0;i--)
            {
                int yo = arr.get(i);
                dp[i]= pow(2,len/yo-1,in);
                for(int j=i+1;j<arr.size();j++)
                {
                    int sal = arr.get(j);
                    if(sal%yo==0)
                    dp[i]= (dp[i]%in-dp[j]%in+in)%in;
                }
            }
            out.println(dp[0]);
       }

    }
    public int gcd(int a , int b )
    {
      if(a<b)
      {
        int t =a;
        a=b;
        b=t;
      }
      if(a%b==0)
        return b ;
      return gcd(b,a%b);
    }
    public long pow(long n , long p,long m)
    {
         if(p==0)
            return 1;
        long val = pow(n,p/2,m);;
        val= (val*val)%m;
        if(p%2==0)
            return val;
        else
            return (val*n)%m;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static void main(String[] args) {
        new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
    }

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    private BufferedReader reader;
    private StringTokenizer tokenizer;
    private PrintWriter out;

    @Override
    public void run() {
        try {
            if (ONLINE_JUDGE || !new File("input.txt").exists()) {
                reader = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                reader = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            }
            solve();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // nothing
            }
            out.close();
        }
    }

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

    @SuppressWarnings("unused")
    private int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    @SuppressWarnings("unused")
    private long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    @SuppressWarnings("unused")
    private double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }
}
class edge implements Comparable<edge>{
    int val ;
    int color;

    edge(int u, int v)
    {
       this.val=u;
       this.color=v;
    }
    public int compareTo(edge e)
    {
        return this.val-e.val;
    }
}


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkgdouble;

import java.util.Scanner;

public class DOUBLE {

 // public long a[][];
    public static double b[][]=new double[2111][1111];
    public static long b1[][]=new long[2111][1111];
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int a,q;
        double m;
        b[1][1]=1;
        b[1][0]=0;

        a=in.nextInt();
        q=in.nextInt();
        m=(double)princess(a+q,a);
        System.out.println(m);

    }

    public static double princess(int n, int w){
      //   System.out.print(n);
      //  System.out.print(" ");
      // System.out.println(w);
        if(b1[n][w]==1)return b[n][w];

        if(n<w)return 0;
            if( w==0)return 0;
            if(n==1)
                if(w==0)return 0; else return 1;
        if(n==w)return 1;
        b1[n][w]=1;
        return b[n][w]=(double)(w*1.0)/n+((double)(n-w)/n)*dragon(n-1,w);
    }
    public static double dragon (int n, int w){
        if(b1[n][w]==1)return b[n][w];
        if(n<w)return 0;
       if( w==0)return 1;
            if(n==1)
                if(w==0)return 1; else return 0;
        if(n==w)return 0;
   //     System.out.prlong("dr");
  //   System.out.prlong(n);
   //     System.out.prlong(" ");
   //    System.out.prlongln(w);

    //    System.out.prlongln((double)(n-w)/n);
  //      System.out.prlongln((((double)w/(n-1))*princess(n-2,w-1)));
   //     System.out.prlongln(((double)(n-1-w)/(n-1))*princess(n-2,w));
        b1[n][w]=1;
        return b[n][w]=((double)(n-w)/n)*(((double)w/(n-1))*princess(n-2,w-1)+((double)(n-1-w)/(n-1))*princess(n-2,w));
    }

}


// 148D - Bag of Mice (Codeforces)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class BagOfMice {
    static final int P = 0; // Princess
    static final int D = 1; // Dragon
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int w,b;
        StringTokenizer st = new StringTokenizer(br.readLine());

        w = Integer.parseInt(st.nextToken());
        b = Integer.parseInt(st.nextToken());

        double dp[][][] = new double[2][w+1][b+1];

        for (int i = 1; i <= w; i++) {
            dp[P][i][0] = 1.0;
            dp[D][i][0] = 1.0;
        }
        for (int j = 0; j <= b; j++) {
            dp[P][0][j] = 0.0;
            dp[D][0][j] = 1.0;
        }
        for (int i = 1; i <= w; i++) {
            dp[P][i][1] = 1.0 * i / (i+1) + (1.0 - dp[D][i][0])/(i+1);
            dp[D][i][1] = 1.0 * i / (i+1) + (1.0 - dp[P][i-1][0])/(i+1);
            for (int j = 2; j <= b; j++) {
                dp[P][i][j] = 1.0 * i / (i+j) + (1.0 - dp[D][i][j-1])*j/(i+j);
                dp[D][i][j] = 1.0 * i / (i+j) + (1.0 - (dp[P][i][j-2]*(j-1)/(i+j-1) + dp[P][i-1][j-1]*i/(i+j-1)))*j/(i+j);
            }
        }
        System.out.printf("%.9f\n", dp[P][w][b]);
    }
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Practice {

	static class length implements Comparator<String>
	{
		public int compare(String a,String b)
		{
			return(a.length()-b.length());
		}
	}

	   static class FastReader
	   {
		   BufferedReader br;
		   StringTokenizer st;
		   public FastReader()
		   {
			   br = new BufferedReader(new InputStreamReader(System.in));
		   }

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

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

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

		public static void main(String []args) throws Exception
		{
			//Scanner sc=new Scanner(System.in);
			FastReader in =new FastReader();
			PrintWriter pw = new PrintWriter(System.out);
			//System.out.println
			//int n=in.nextInt();

			int n=in.nextInt();
			int l=in.nextInt();
			int r=in.nextInt();
			int min=n-(l-1);
			int i=1;
			while(i<=(l-1))
			{
				min=min+(int)Math.pow(2, i);
				i++;
			}
			i=0;
			int max=0;
			int max1=0,k=0;
			while(i!=r)
			{
				max1=(int)Math.pow(2,i);
				max=max+max1;
				i++;
				k++;

				//pw.println(max+" "+max1);
			}
			max=max+max1*(n-k);
			//pw.println(max);
			pw.print(min+" "+max);


public class main {

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		String s1 = sc.nextLine();
		String s[] = s1.split(" ");
		int a[] = Arrays.stream(s).mapToInt(Integer::parseInt).toArray();
		int min =0,x=0,max=0,l = a[1]-1,r=a[2],n=a[0];
		min += (n-l);
		while(l>0) {
			min += Math.pow(2, l);
			l--;
		}
		while(x<r) {
			max += Math.pow(2, x);
			x++;
		}
		if((n-r)!=0) {
			max += ((n-r)*(Math.pow(2,x-1)));
		}
		System.out.println(min+" "+max);
	}
}


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

public class Codeforces933D {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		long n = Integer.parseInt(st.nextToken());

		int counter = 0;
		int N = 1000000007;

		for (int i = 0; i < 500000; i++) {
			counter += firstsum(n, 4*i+1);
			counter -= firstsum(n, 4*i+3);
			counter %= N;
		}

		for (int b = 1; b <= n/2000000; b++) {
			counter += secondsum(n, b);
			counter %= N;
		}

		int ans = (2*((2*counter)%N))%N;
		long k = ((((((n%N)*(n%N+1))%N)*(n%N+2))%N)*166666668)%N;
		ans = (ans + (int) k)%N;
		System.out.println(ans);
	}

	//1/2 = 500000004
	//1/3 = 333333336
	//1/6 = 166666668
	//lmao
	public static int firstsum(long n, long q) {
		int N = 1000000007;
		long floornq = (n/q)%N;
		n %= N;
		q %= N;
		long sum = ((floornq*(floornq+1))/2)%N;
		long sumsquare = (((sum*(2*floornq+1))%N)*333333336)%N;
		long sumcube = (sum*sum)%N;
		long nsquare = (n*n)%N;
		long qsquare = (q*q)%N;
		long qcube = (q*qsquare)%N;

		long k1 = (nsquare*floornq - qsquare*sumsquare + n*floornq + q*sum)%N;
		if (k1 < 0)
			k1 += N;
		k1 = (k1*(n+1))%N;
		k1 = (k1*500000004)%N;

		long k2 = (((((n*(n+1))%N)*(2*n+1))%N)*166666668)%N;
		k2 = (k2*floornq)%N;

		long k3 = (((qcube*sumcube)%N)*333333336)%N;
		k3 -= (((qsquare*sumsquare)%N)*500000004)%N;
		k3 += (((q*sum)%N)*166666668)%N;

		long ans = (k1-k2+k3)%N;
		if (ans < 0)
			ans += N;
		return (int) ans;
	}

	//wtf who successfully codes this up in a real round?
	public static int secondsum(long n, long b) {
		int N = 1000000007;
		long bsquare = (b*b)%N;
		long bcube = (b*bsquare)%N;
		long max = (n/(4*b)-1)%N;
		long numk = (max + N + 1 - 500000)%N;
		long sumk = ((max)*(max+1)/2 + 250875)%N;
		long sumksquare = ((((long) max * (long) (max+1))%N * (long) (2*max + 1))%N * 166666668)%N-375084213;
		if (sumksquare < 0)
			sumksquare += N;

		long k1 = (((bcube*sumksquare)%N)*32)%N;
		long k2 = (((bsquare*sumk)%N * (4*b-1)%N)%N *8)%N;
		long k3 = ((26*bcube - 12*bsquare + b)%N * 333333336)%N;
		if (k3 < 0)
			k3 += N;
		k3 = (k3*numk)%N;
		long k4 = (((n+1)%N)*(b*(numk*(((4*b*500000 + 4*b*max)+4*b-1)%N)%N)%N))%N;

		long k5 = 0;
		long k6 = 0;

		if (n%(4*b) >= b) {
			long min2 = ((4*b)*(n/(4*b))+b)%N;
			long max2 = (Math.min((4*b)*(n/(4*b))+3*b-1, n))%N;
			//sum from min2 to max2 of (n+1-i)*i
			k5 = (((((max2*(max2+1))%N)*(2*max2+1))%N)*166666668)%N;
			k5 -= (((((((min2-1)*min2)%N)*(2*min2-1))%N)*166666668)%N);
			k6 = ((max2*(max2+1) - min2*(min2-1))/2)%N;
			k6 = (k6*((n+1)%N))%N;
			System.out.println(k6);
		}

		return (int) ((k4-k1-k2-k3-k5+k6+7*(long)N)%N);
	}

}


//package round462;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class D3 {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		long m = nl();
		int mod = 1000000007;
		long mm = m%mod;
		long ans = 0;
		for(long x = 1;x*x <= m;x++){
			long n = (long)Math.sqrt(m-x*x);
			ans += invl(420, mod) * (n+1) % mod
					* (70*mm%mod*mm%mod*mm+210*mm%mod*mm
							-42*mm%mod*n%mod*n%mod*n%mod*n%mod
							-63*mm%mod*n%mod*n%mod*n%mod
							-140*mm%mod*n%mod*n%mod*x%mod*x%mod
							+63*mm%mod*n%mod*n%mod
							-70*mm%mod*n%mod*x%mod*x%mod
							+42*mm%mod*n%mod
							-210*mm%mod*x%mod*x%mod*x%mod*x%mod
							+210*mm%mod*x%mod*x%mod
							+140*mm%mod
							+20*n%mod*n%mod*n%mod*n%mod*n%mod*n%mod
							+50*n%mod*n%mod*n%mod*n%mod*n%mod
							+84*n%mod*n%mod*n%mod*n%mod*x%mod*x%mod
							-64*n%mod*n%mod*n%mod*n%mod
							+126*n%mod*n%mod*n%mod*x%mod*x%mod
							-146*n%mod*n%mod*n%mod
							+140*n%mod*n%mod*x%mod*x%mod*x%mod*x%mod
							-266*n%mod*n%mod*x%mod*x%mod
							+76*n%mod*n%mod
							+70*n%mod*x%mod*x%mod*x%mod*x%mod
							-154*n%mod*x%mod*x%mod
							+64*n%mod
							+140*x%mod*x%mod*x%mod*x%mod*x%mod*x%mod
							-420*x%mod*x%mod*x%mod*x%mod
							+280*x%mod*x%mod
							)%mod;
		}
		ans = ans * 4 + mm*(mm+1)%mod*(mm+2)%mod*invl(6,mod)%mod;
		ans %= mod;
		if(ans < 0)ans += mod;
		out.println(ans);
	}

	public static long invl(long a, long mod) {
		long b = mod;
		long p = 1, q = 0;
		while (b > 0) {
			long c = a / b;
			long d;
			d = a;
			a = b;
			b = d % b;
			d = p;
			p = q;
			q = d - c * q;
		}
		return p < 0 ? p + mod : p;
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

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

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


// Don't place your source in a package
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;

 /*

 6666666666666			 6666666666666
 6						 6
 6						 6
 6						 6
 6						 6
 6                       6
 6666666666666           6666666666666
 6		     6           6		     6
 6			 6	         6			 6
 6			 6           6			 6
 6		     6	         6		     6
 6666666666666           6666666666666

 */

// Please name your class Main
public class Main {

	//static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    /*static int read() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }
    static String readString() throws IOException {
        in.nextToken();
        return in.sval;
	}*/

	static Scanner in = new Scanner(System.in);

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

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

		int T=1;

		for(int t=0;t<T;t++){
			int K=Int();
			int F[]=new int[6];
			for(int i=0;i<6;i++){
				F[i]=Int();
			}

			int q=Int();
			int W=Int();

			Solution sol=new Solution();
			sol.solution(K,F,W);
		}

		out.flush();
	}

	public static int Int(){
		return in.nextInt();
	}
	public static String Str(){
		return in.next();
	}
}

class Solution{
	//constant variable
	final int MAX=Integer.MAX_VALUE;
	final int MIN=Integer.MIN_VALUE;
	//Set<Integer>adjecent[];
	//////////////////////////////

	public void solution(int K,int F[],int W){
		long res=0;
		int ten[]=new int[]{1,10,100,1000,10000,100000};

		//0-1 knapsack, creating items
		List<Item>A=new ArrayList<>();

		K--;//extra number
		for(int i=0;i<6;i++){//1 10 100 1000 10000 10000
			long weight=ten[i]*3;//single weight
			int cur=0;
			for(int j=0;j<32;j++){
				int go=1<<j;
				if(cur+go>=(3*K)){
					int remain=3*K-cur;
					Item item=new Item(weight*remain,F[i]*remain,i);
					A.add(item);
					break;
				}
				Item item=new Item(weight*(1<<j),F[i]*(1<<j),i);
				cur+=(1<<j);
				A.add(item);
			}
		}

		//System.out.println(A);

		/*long dp[][]=new long[6][W+1];
		for(int i=0;i<dp.length;i++){
			Arrays.fill(dp[i],-1);
		}

		//knapsack on each  digit
		for(int i=0;i<6;i++){
			List<Item>items=A[i];
			long max=ten[i]*9*K;
			dp[i][0]=0;
			for(Item item:items){
				int w=(int)(item.w);
				long val=item.val;
				for(int j=1;j<=Math.min(max,W);j++){
					if(w>j)continue;
					if(dp[i][j-w]!=-1){
						dp[i][j]=Math.max(dp[i][j],dp[i][j-w]+val);
					}
				}
			}
			print1(dp[i]);
		}*/

		long dp[][]=new long[A.size()+1][W+1];

		for(int i=0;i<dp.length;i++){
			Arrays.fill(dp[i],-1);
		}
		dp[0][0]=0;

		for(int i=1;i<dp.length;i++){
			Item item=A.get(i-1);
			dp[i][0]=0;
			for(int j=1;j<dp[0].length;j++){
				dp[i][j]=Math.max(dp[i][j],dp[i-1][j]);
				int w=(int)(item.w);
				long val=item.val;
				if(j<w||dp[i-1][j-w]==-1){
					//msg1(dp[i][j]+" ");
					continue;
				}
				dp[i][j]=Math.max(dp[i][j],dp[i-1][j-w]+val);
				//msg1(dp[i][j]+" ");
				String num=(W-j)+"";
				StringBuilder str=new StringBuilder(num);
				num=str.reverse().toString();
				long score=0;
				for(int k=0;k<num.length();k++){
					int d=num.charAt(k)-'0';
					if(d%3==0){
						score+=(F[k]*(d/3));
					}
				}

				res=Math.max(res,dp[i][j]+score);

			}//msg("");
		}

		msg(res+"");

	}

	class Item{
		long w=0;
		long val=0;
		int group;
		public Item(long w,long val,int group){
			this.w=w;
			this.val=val;
			this.group=group;
		}

		public String toString(){
			return w+"  "+val+"   "+group+"  \n";
		}
	}

	public void swap(int A[],int l,int r){
		int t=A[l];
		A[l]=A[r];
		A[r]=t;
	}

	public long C(long fact[],int i,int j){ // C(20,3)=20!/(17!*3!)
		// take   a/b     where a=20!  b=17!*3!
		if(j>i)return 0;
		if(j==0)return 1;
		long mod=1000000007;
		long a=fact[i];
		long b=((fact[i-j]%mod)*(fact[j]%mod))%mod;
		BigInteger B= BigInteger.valueOf(b);
		long binverse=B.modInverse(BigInteger.valueOf(mod)).longValue();
		return ((a)*(binverse%mod))%mod;
	}

	//map operation
	public void put(Map<Integer,Integer>map,int i){
		if(!map.containsKey(i))map.put(i,0);
		map.put(i,map.get(i)+1);
	}

	public void delete(Map<Integer,Integer>map,int i){
		map.put(i,map.get(i)-1);
		if(map.get(i)==0)map.remove(i);
	}

	/*public void tarjan(int p,int r){
		if(cut)return;
		List<Integer>childs=adjecent[r];
		dis[r]=low[r]=time;
		time++;

		//core for tarjan
		int son=0;
		for(int c:childs){
			if(ban==c||c==p)continue;
			if(dis[c]==-1){
				son++;
				tarjan(r,c);
				low[r]=Math.min(low[r],low[c]);
				if((r==root&&son>1)||(low[c]>=dis[r]&&r!=root)){
					cut=true;
					return;
				}
			}else{
				if(c!=p){
					low[r]=Math.min(low[r],dis[c]);
				}
			}
		}

	}*/

	//helper function I would use
	public void remove(Map<Integer,Integer>map,int i){
		map.put(i,map.get(i)-1);
		if(map.get(i)==0)map.remove(i);
	}

	public void ascii(String s){
		for(char c:s.toCharArray()){
			System.out.print((c-'a')+" ");
		}
		msg("");
	}

	public int flip(int i){
		if(i==0)return 1;
		else return 0;
	}

	public boolean[] primes(int n){
		boolean A[]=new boolean[n+1];
		for(int i=2;i<=n;i++){
			if(A[i]==false){
				for(int j=i+i;j<=n;j+=i){
					A[j]=true;
				}
			}
		}
		return A;
	}

	public void msg(String s){
		System.out.println(s);
	}

	public void msg1(String s){
		System.out.print(s);
	}

	public int[] kmpPre(String p){
		int pre[]=new int[p.length()];
		int l=0,r=1;
		while(r<p.length()){
			if(p.charAt(l)==p.charAt(r)){
				pre[r]=l+1;
				l++;r++;
			}else{
				if(l==0)r++;
				else l=pre[l-1];
			}
		}
		return pre;
	}

	public boolean isP(String s){
		int l=0,r=s.length()-1;
		while(l<r){
			if(s.charAt(l)!=s.charAt(r))return false;
			l++;r--;
		}
		return true;
	}

	public int find(int nums[],int x){//union find => find method
		if(nums[x]==x)return x;
		int root=find(nums,nums[x]);
		nums[x]=root;
		return root;
	}

	public int get(int A[],int i){
		if(i<0||i>=A.length)return 0;
		return A[i];
	}
	public int[] copy1(int A[]){
		int a[]=new int[A.length];
		for(int i=0;i<a.length;i++)a[i]=A[i];
		return a;
	}

	public void print1(long A[]){
		for(long i:A)System.out.print(i+" ");
		System.out.println();
	}
	public void print2(int A[][]){
		for(int i=0;i<A.length;i++){
			for(int j=0;j<A[0].length;j++){
				System.out.print(A[i][j]+" ");
			}System.out.println();
		}
	}

	public int min(int a,int b){
		return Math.min(a,b);
	}

	public int[][] matrixdp(int[][] grid) {
        if(grid.length==0)return new int[][]{};
        int res[][]=new int[grid.length][grid[0].length];
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                res[i][j]=grid[i][j]+get(res,i-1,j)+get(res,i,j-1)-get(res,i-1,j-1);
            }
        }
        return res;
    }

    public int get(int grid[][],int i,int j){
        if(i<0||j<0||i>=grid.length||j>=grid[0].length)return 0;
        return grid[i][j];
    }

	public int[] suffixArray(String s){
		int n=s.length();
		Suffix A[]=new Suffix[n];

		for(int i=0;i<n;i++){
			A[i]=new Suffix(i,s.charAt(i)-'a',0);
		}

		for(int i=0;i<n;i++){
			if(i==n-1){
				A[i].next=-1;
			}else{
				A[i].next=A[i+1].rank;
			}
		}
		Arrays.sort(A);

		for(int len=4;len<A.length*2;len<<=1){
			int in[]=new int[A.length];
			int rank=0;
			int pre=A[0].rank;
			A[0].rank=rank;
			in[A[0].index]=0;
			for(int i=1;i<A.length;i++){//rank for the first two letter
				if(A[i].rank==pre&&A[i].next==A[i-1].next){
					pre=A[i].rank;
					A[i].rank=rank;
				}else{
					pre=A[i].rank;
					A[i].rank=++rank;
				}
				in[A[i].index]=i;
			}

			for(int i=0;i<A.length;i++){
				int next=A[i].index+len/2;
				if(next>=A.length){
					A[i].next=-1;
				}else{
					A[i].next=A[in[next]].rank;
				}
			}

			Arrays.sort(A);
		}

		int su[]=new int[A.length];
		for(int i=0;i<su.length;i++){
			su[i]=A[i].index;
		}
		return su;
	}

}

//suffix array Struct
class Suffix implements Comparable<Suffix>{
	int index;
	int rank;
	int next;
	public Suffix(int i,int rank,int next){
		this.index=i;
		this.rank=rank;
		this.next=next;
	}

	@Override
	public int compareTo(Suffix other) {
		if(this.rank==other.rank){
			return this.next-other.next;
		}
		return this.rank-other.rank;
	}

	public String toString(){
		return this.index+"   "+this.rank+"   "+this.next+"  ";
	}
}

class Wrapper implements Comparable<Wrapper>{
	int spf;int cnt;
	public Wrapper(int spf,int cnt){
		this.spf=spf;
		this.cnt=cnt;
	}

	@Override
	public int compareTo(Wrapper other) {
		return this.spf-other.spf;
	}
}

    class Node{//what the range would be for that particular node
		boolean state=false;
        int l=0,r=0;
		int ll=0,rr=0;
        public Node(boolean state){
            this.state=state;
        }
    }

	class Seg1{
			int A[];
			public Seg1(int A[]){
				this.A=A;
			}

			public void update(int left,int right,int val,int s,int e,int id){
				if(left<0||right<0||left>right)return;
				if(left==s&&right==e){

					A[id]+=val;
					return;
				}
				int mid=s+(e-s)/2; //[s,mid] [mid+1,e]

				if(left>=mid+1){
					update(left,right,val,mid+1,e,id*2+2);
				}else if(right<=mid){
					update(left,right,val,s,mid,id*2+1);
				}else{
					update(left,mid,val,s,mid,id*2+1);
					update(mid+1,right,val,mid+1,e,id*2+2);
				}
			}

			public int query(int i,int add,int s,int e,int id){

				if(s==e&&i==s){
					return A[id]+add;
				}

				int mid=s+(e-s)/2; //[s,mid] [mid+1,e]

				if(i>=mid+1){
					return query(i,A[id]+add,mid+1,e,id*2+2);
				}else{
					return query(i,A[id]+add,s,mid,id*2+1);
				}
			}
	}

	 class MaxFlow{

		  public static List<Edge>[] createGraph(int nodes) {
			List<Edge>[] graph = new List[nodes];
			for (int i = 0; i < nodes; i++)
			  graph[i] = new ArrayList<>();
			return graph;
		  }

		  public static void addEdge(List<Edge>[] graph, int s, int t, int cap) {
			graph[s].add(new Edge(t, graph[t].size(), cap));
			graph[t].add(new Edge(s, graph[s].size() - 1, 0));
		  }

		  static boolean dinicBfs(List<Edge>[] graph, int src, int dest, int[] dist) {
			Arrays.fill(dist, -1);
			dist[src] = 0;
			int[] Q = new int[graph.length];
			int sizeQ = 0;
			Q[sizeQ++] = src;
			for (int i = 0; i < sizeQ; i++) {
			  int u = Q[i];
			  for (Edge e : graph[u]) {
				if (dist[e.t] < 0 && e.f < e.cap) {
				  dist[e.t] = dist[u] + 1;
				  Q[sizeQ++] = e.t;
				}
			  }
			}
			return dist[dest] >= 0;
		  }

		  static int dinicDfs(List<Edge>[] graph, int[] ptr, int[] dist, int dest, int u, int f) {
			if (u == dest)
			  return f;
			for (; ptr[u] < graph[u].size(); ++ptr[u]) {
			  Edge e = graph[u].get(ptr[u]);
			  if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {
				int df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f));
				if (df > 0) {
				  e.f += df;
				  graph[e.t].get(e.rev).f -= df;
				  return df;
				}
			  }
			}
			return 0;
		  }

		  public static int maxFlow(List<Edge>[] graph, int src, int dest) {
			int flow = 0;
			int[] dist = new int[graph.length];
			while (dinicBfs(graph, src, dest, dist)) {
			  int[] ptr = new int[graph.length];
			  while (true) {
				int df = dinicDfs(graph, ptr, dist, dest, src, Integer.MAX_VALUE);
				if (df == 0)
				  break;
				flow += df;
			  }
			}
			return flow;
		  }

	 }

	 	 class Edge {
			int t, rev, cap, f;

			public Edge(int t, int rev, int cap) {
			  this.t = t;
			  this.rev = rev;
			  this.cap = cap;
			}
		  }

    class Seg{
        int l,r;
        int min=Integer.MAX_VALUE;
        Seg left=null,right=null;
		long sum=0;long cnt=0;
        public Seg(int l,int r){
            this.l=l;
            this.r=r;

        }
        public long[] query(int s,int e){
            if(l==s&&r==e){
                return new long[]{sum,cnt};
            }
            int mid=l+(r-l)/2; //left :  to mid-1,

			if(left==null)left=new Seg(l,mid);
			if(right==null)right=new Seg(mid+1,r);

			if(e<=mid){
                return left.query(s,e);
            }
            else if(s>=mid+1){
                return right.query(s,e);
            }else{
				long A[]=left.query(s,mid);
				long B[]=right.query(mid+1,e);
				return new long[]{A[0]+B[0],A[1]+B[1]};

            }
        }

        public void update(int index,int v){
			sum+=v;
			cnt++;
            if(l==r&&l==index){
                return;
            }
            int mid=l+(r-l)/2;
            if(index<=mid){
				if(left==null)left=new Seg(l,mid);
                left.update(index,v);
            }else{
				if(right==null)right=new Seg(mid+1,r);
                right.update(index,v);
            }

        }
    }


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

public class Main{
	static int maxn=1000000;
	static long inf=(long)1e16;
	static long fill=(long)-1e18;
	static ArrayList<Integer>weights;
	static ArrayList<Long>vals;
	static long[][]memo;
	static long dp(int i,int sum) {
		if(i>=weights.size())return sum==0?0:-inf;
		if(sum<0)return -inf;
		if(memo[i][sum]!=fill)return memo[i][sum];
		return memo[i][sum]=Math.max(dp(i+1, sum), vals.get(i)+dp(i+1, sum-weights.get(i)));
	}
	static int[]F;
	static long cost(int num) {
		int d=0;
		long ans=0;
		while(num>0) {
			int digit=num%10;
			num/=10;
			if(digit==3 || digit==6 || digit==9) {
				ans+=F[d]*(digit/3);
			}
			d++;
		}
		return ans;
	}
	static void main() throws Exception{
		int n=(sc.nextInt()-1)*3;
		F=sc.intArr(6);
		vals=new ArrayList<Long>();
		weights=new ArrayList<Integer>();
		int ten=1;
		for(int i=0;i<6;i++) {
			int curW=3*ten;long curV=F[i];
			int cur=1;
			while(cur<=n) {
				if(curW*1l*cur>maxn)break;
				weights.add(curW*cur);
				vals.add(curV*cur);
				n-=cur;
				cur<<=1;
			}
			if(n>0 && curW*1l*n<=maxn) {
				weights.add(curW*n);
				vals.add(curV*n);
			}
			ten*=10;
		}
		memo=new long[weights.size()][maxn];
		for(int i=0;i<memo.length;i++) {
			for(int j=0;j<maxn;j++) {
				memo[i][j]=fill;
			}
		}
		int q=sc.nextInt();
		while(q-->0) {
			int sum=sc.nextInt();
			long ans=-inf;
			for(int i=0;i<=sum;i++) {
				ans=Math.max(cost(i)+dp(0, sum-i),ans);
			}
			pw.println(ans);
		}
	}
	public static void main(String[] args) throws Exception{
		sc=new MScanner(System.in);
		pw = new PrintWriter(System.out);
//		int tc=1;
//		tc=sc.nextInt();
//		while(tc-->0)
			main();
		pw.flush();
	}
	static PrintWriter pw;
	static MScanner sc;
	static class MScanner {
		StringTokenizer st;
		BufferedReader br;
		public MScanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public MScanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}
		public int[] intArr(int n) throws IOException {
	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public long[] longArr(int n) throws IOException {
	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public int[] intSortedArr(int n) throws IOException {
	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        shuffle(in);
	        Arrays.sort(in);
	        return in;
		}
		public long[] longSortedArr(int n) throws IOException {
	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        shuffle(in);
	        Arrays.sort(in);
	        return in;
		}
		public Integer[] IntegerArr(int n) throws IOException {
	        Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public Long[] LongArr(int n) throws IOException {
	        Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}

	}
	static void shuffle(int[]in) {
		for(int i=0;i<in.length;i++) {
			int idx=(int)(Math.random()*in.length);
			int tmp=in[i];
			in[i]=in[idx];
			in[idx]=tmp;
		}
	}
	static void shuffle(long[]in) {
		for(int i=0;i<in.length;i++) {
			int idx=(int)(Math.random()*in.length);
			long tmp=in[i];
			in[i]=in[idx];
			in[idx]=tmp;
		}
	}
}


//package JustTasks;//package JustTasks;

import java.util.Arrays;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long a = in.nextLong();
        long b = in.nextLong();
        long d = in.nextLong();
        long counter = 0;
        while (a!=0){
            a--;
            counter++;
        }
        while (b!=0){
            b--;
            counter++;
        }
        if(counter<=d && (d-counter)%2==0){
            System.out.println("YES");
        }
        else {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class FiveinARow {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner input = new Scanner(System.in);
		char[][] s = new char[10][10];
		for(int i=0; i<10;i++){
			s[i] = input.next().toCharArray();

		}
		//System.out.println(check1(s,0,4));
		for(int i=0; i<10;i++){
			for(int j=0; j<10;j++){
				if( i>=4){
					if(checkrow( s,  i,j)){
						System.out.println("YES");
						//System.out.println(i+" "+j);
						return;
					}
				}
				if(j>=4){
					if(checkcolumn(s,i,j)){
						System.out.println("YES");
						//System.out.println(i+" "+j+"d");
						return;
					}
				}
				if(i>=4 && j>=4){
					if(check(s,i,j)){
						System.out.println("YES");
						//System.out.println(i+" "+j+"s");
						return;
					}
				}
				if(i<=6 && j>=4){
					if(check1(s,i,j)){
						System.out.println("YES");
						return;
					}
				}
			}
		}
		System.out.println("NO");

	}

	private static boolean checkrow(char[][] s, int i, int j){
		int crosses = 0;
		int dots=0;
		for(int tmp=i-4; tmp<=i;tmp++){
			if(s[tmp][j]=='X')crosses++;
			else if(s[tmp][j]=='.')dots++;
		}
		if((dots==0 && crosses==5) ||(dots==1 && crosses==4) )return true;
		else
			return false;
	}
	private static boolean checkcolumn(char[][] s, int i,int j){
		int crosses=0;
		int dots=0;
		for(int tmp = j-4;tmp<=j;tmp++){
			if(s[i][tmp]=='X')crosses++;
			else if(s[i][tmp]=='.')dots++;
		}
		if((dots==0 && crosses==5) ||(dots==1 && crosses==4) ){
			//System.out.println(dots+" "+crosses);
			return true;
		}
		else
			return false;
	}

	private static boolean check(char[][] s, int i, int j){
		int tmp2 = i-4;
		int crosses=0;
		int dots=0;
		for(int tmp=j-4; tmp<=j;tmp++){
			if(s[tmp2][tmp]=='X')crosses++;
			else
				if(s[tmp2][tmp]=='.')dots++;
		   tmp2++;
		}
		if((dots==0 && crosses==5) ||(dots==1 && crosses==4) )return true;
		else
			return false;

	}

	private static boolean check1(char[][] s,int i, int j){
		int tmp2 = j-4;
		int crosses=0;
		int dots=0;
		for(int tmp=i+4;tmp>=i;tmp--){
			if(s[tmp][tmp2]=='X')crosses++;
			else
				if(s[tmp][tmp2]=='.')dots++;
			tmp2++;
		}
		if((dots==0 && crosses==5) ||(dots==1 && crosses==4) )return true;
		else
			return false;
	}

}


import java.util.*;
public class Q869B
{
	public static void main(String dfg[])
	{
		Scanner sc=new Scanner(System.in);
		int a=sc.nextInt();
		int b=sc.nextInt();
		int c=b-a;
		if(a==b)
		{
		System.out.println("1");

		}
		int c=b-a;
		else if(c==1)
		{
		System.out.println(b%10);

		}
		else
		{
		int f=1;
		for(int x=1;x<=c;x++)
		{
			f=f*b--;

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


import java.util.*;
public class k {

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

		int count=0;
		for(int i=1; i<=n; i++)
		{
			if((i%2!=0)&&(i%3!=0)&&(i%5!=0)&&(i%7!=0))
				count++;
		}
		System.out.println(count);
	}

}


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jose
 */
public class Botones {

}


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

public class Main {

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

	static final int oo = (int)1e9;
	static int M = 105;

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

		int s = in.nextInt();
		int x1 = in.nextInt();
		int x2 = in.nextInt();

		int t1 = in.nextInt();
		int t2 = in.nextInt();

		int p = in.nextInt();
		int d = in.nextInt();

		int dist = Math.abs(x2 - x1);
		int distb = 0;
		int l, r;
		while(true) {
			if(p == x2) {
				if(d == 1) {
					l = x2;
					r = s;
					distb += (s - x2) * 2;
				}
				else {
					l = 0;
					r = x2;
					distb += 2 * x2;
				}
			}
			else {
				if( Integer.signum(x2 - p) == Integer.signum(d) ) {
					l = Math.min(x2, p);
					r = Math.max(x2, p);
					distb += Math.abs(x2 - p);
				}
				else if(d == -1) {
					l = 0;
					r = x2;
					distb += (p + x2);
				}
				else {
					l = x2;
					r = s;
					distb += (2 * s - p - x2);
				}
				p = x2;
			}
			if(l <= x1 && x1 <= r)
				break;
		}

		int ans = Math.min( dist * t2, distb * t1 );
		System.out.println(ans);

		out.close();
	}

	static int lower_bound(long[] a, int n, long k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}
}

class InputReader {

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

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

	public int read() {
		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 = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			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 {
			res *= 10;
			res += c - '0';
			c = read();
		} 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 = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

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

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

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

}


import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author muath
 */
public class Basic {

    public static void main(String[] args) {
        // TODO code application logic here
       Scanner input = new Scanner(System.in);
       int counter=0;
       String []  numbers = input.nextLine().split(" ");
       int home=Integer.parseInt(numbers[1])-1;
       String [] numbers2 = input.nextLine().split(" ");
       ArrayList<Integer> list= new ArrayList<Integer>();
       for(int i =0 ; i<numbers2.length;i++)
       {
        list.add(Integer.parseInt(numbers2[i]));
       }
       if(list.get(home)==1)
           counter+=1;
       int temp=0;
      if(list.size()>1)
      {
      if(home <list.size()/2)
      {
          int i ,k,j;
      for( i=home+1,k=home,j=home ; k-1>=0;i++,k--)
      {

              if(i-1 >=0 &&(list.get(k)==list.get(i)) && list.get(i)!=0)
              {

                  counter+=2;
              }

      }

      for(int z=i;z<list.size();z++)
      {

          if(list.get(z)==1)
          {

              counter+=1;
          }
      }
      }
      else
      {
          int i , k , j;
          for( i=home+1,k=home-1,j=home;i<list.size();i++,k--)
          {
              if(i < list.size() &&(list.get(i))==list.get(k) && list.get(i)!=0)
                  counter+=2;
          }
          for(int z=k;z>=0;z++)
          {
              if(list.get(z)==1)
                  counter+=1;
          }
      }
      }

   System.out.println(counter);

}

}


package block_towers;

import java.util.Scanner;

/**
 *
 * @author Chucho
 */
public class Block_Towers {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt(), M = in.nextInt(), C, TopM, TopN;
        String Case;
        C = Math.min(N / 3, M / 2);
        TopN = 2 * N;
        TopM = 3 * M;
        while (C > 0) {
            if (TopN == TopM){
                TopN += 2;
                C--;
                Case = " 1";
            } else if (TopN > TopM) {
                if (TopN > (TopM + 3) && (TopM + 3) / 2 != 0) {
                    TopM += 3;
                    C--;
                    Case = " 2";
                } else if (TopN < (TopM + 3)) {
                    TopM += 3;
                    C--;
                    Case = " 3";
                } else{
                    TopM += 3;
                    Case = " 4";
                }
            } else {
                if ((TopN + 2) / 6 != 0 && TopM != (TopN + 2)) {
                    TopN += 2;
                    C--;
                    Case = " 5";
                } else{
                    TopN += 2;
                    Case = " 6";
                }
            }
            //System.out.println(C + " " + TopN + " " + TopM + Case);
        }
        System.out.println(Math.max(TopM, TopN));
    }
}


import java.util.Scanner;

public class Solution {

	public static long gcd(long a, long b) {
		while(a > 0) {
			long r = b % a;
			b = a;
			a = r;
		}
		return b;
	}

	public static long f(long a, long b) {
		if( b == 0) return 0;
		if( b % a == 0) {
			return b/a;
		}
		if( a % b == 0) return 1;
		long g= gcd(Math.min(a, b), Math.max(a, b));
		return 1 + f(a,b - g);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		long a = in.nextLong();
		long b = in.nextLong();
		System.out.println(f(a,b));
		in.close();
	}

}


import java.util.Scanner;

public class helpVasilisa {
    public static void main(String[] args){
        Scanner input=new Scanner(System.in);
        int r1=input.nextInt();
        int r2=input.nextInt();
        int c1=input.nextInt();
        int c2=input.nextInt();
        int d1=input.nextInt();
        int d2=input.nextInt();
        int rlc,ruc,luc,llc;
        if(d1<10){
            rlc=d1-1;
            luc=d1-rlc;
        }else{
            rlc=9;
            luc=d1-rlc;
        }
        while(true){
            llc=c1-luc;
            if(llc>=10||(llc+rlc)!=r2){
                rlc--;
                luc++;
                continue;
            }
            if(rlc<=0||luc>10){
                System.out.println("-1");
                return;
            }
            break;
        }
        ruc=c2-rlc;
        if(ruc>10||ruc<=0||ruc==luc||ruc==rlc||rlc==luc||rlc==llc||llc==luc){
            System.out.println(-1);
        }else{
            System.out.println(luc+" "+ruc);
            System.out.println(llc+" "+rlc);
        }
    }
}


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

public class Codeforces913F {
	public static void main(String[] args) throws IOException {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int a = input.nextInt();
		int b = input.nextInt();
		input.close();
		final int mod = 998244353;

		int frac = multiply(a, inverse(b, mod), mod);
		int reverse = (mod+1-frac)%mod;

		int[] fracpower = new int[n+1];
		int[] reversepower = new int[n+1];
		fracpower[0] = 1;
		reversepower[0] = 1;
		for (int i = 1; i <= n; i++) {
			fracpower[i] = multiply(fracpower[i-1], frac, mod);
			reversepower[i] = multiply(reversepower[i-1], reverse, mod);
		}

		int[][] dp1 = new int[n+1][n+1];
		dp1[2][1] = 1;
		for (int i = 3; i <= n; i++) {
			for (int j = 1; j < i; j++) {
				if (j == 1) {
					dp1[i][j] = fracpower[i-1];
				}
				else {
					dp1[i][j] = multiply(dp1[i-1][j-1], fracpower[i-j], mod);
				}
				if (j == i-1) {
					dp1[i][j] += reversepower[i-1];
					dp1[i][j] %= mod;
				}
				else {
					dp1[i][j] += multiply(dp1[i-1][j], reversepower[j], mod);
					dp1[i][j] %= mod;
				}
			}
		}

		int[][] dp2 = new int[n+1][n+1];
		dp2[1][1] = 1;
		dp2[2][1] = 1;
		dp2[2][2] = 0;
		for (int i = 3; i <= n; i++) {
			int val = 0;
			for (int j = 1; j < i; j++) {
				dp2[i][j] = multiply(dp2[j][j], dp1[i][j], mod);
				val += dp2[i][j];
				val %= mod;
			}
			dp2[i][i] = (mod+1-val)%mod;
		}

		for (int i = 2; i <= n; i++) {
			for (int j = 1; j <= i; j++) {
				System.out.print(dp2[i][j] + " ");
			}
			System.out.println();
		}

		int[] EV = new int[n+1];
		EV[1] = 0;
		EV[2] = 1;
		for (int i = 3; i <= n; i++) {
			int val = 0;
			for (int j = 1; j < i; j++) {
				int r = j*(i-j) + (j*(j-1))/2 + EV[i-j] + EV[j];
				r %= mod;
				val += multiply(dp2[i][j], r, mod);
				val %= mod;
			}
			val += multiply((i*(i-1))/2, dp2[i][i], mod);
			val %= mod;

			int s = (mod+1-dp2[i][i])%mod;
			EV[i] = multiply(val, inverse(s, mod), mod);
		}

		System.out.println(EV[n]);
	}

	public static int multiply(int a, int b, int mod) {
		long x = (long)a*(long)b;
		return (int) (x%mod);
	}

	public static int inverse (int a, int n) {
		int m = n;
		int r1 = 1;
		int r2 = 0;
		int r3 = 0;
		int r4 = 1;
		while ((a > 0) && (n > 0)) {
			if (n >= a) {
				r3 -= r1*(n/a);
				r4 -= r2*(n/a);
				n = n%a;
			}
			else {
				int tmp = a;
				a = n;
				n = tmp;
				tmp = r1;
				r1 = r3;
				r3 = tmp;
				tmp = r2;
				r2 = r4;
				r4 = tmp;
			}
		}
		if (a == 0) {
			if (r3 >= 0)
				return (r3%m);
			else
				return (m+(r3%m));
		}
		else {
			if (r1 >= 0)
				return (r1%m);
			else
				return (m+(r1%m));
		}

	}
}


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.lang.Long;

public class Test {
	static long mod = 1000000007;
	static int[][][][] dp;
	static boolean[][][][] check;
	static int contains;

	public static void main(String[] args) throws FileNotFoundException {
		PrintWriter out = new PrintWriter(System.out);
		Scanner in = new Scanner();
		int n = in.nextInt();
		int x = in.nextInt() - 1;
		int y = in.nextInt() - 1;
		long c = in.nextLong();
		int start = 0;
		int end = 2 * n;
		long result = end;
		while (start <= end) {
			int mid = (start + end) / 2;
			long total = 0;
			for (int i = Math.max(0, x - mid); i <= Math.min(n - 1, x + mid); i++) {
				int v = mid - Math.abs(i - x);
				long min = Math.max(0, y - v);
				long max = Math.min(n - 1, y + v);
				total += max - min + 1;

			}
			if(total < c){
				start = mid + 1;
			}else if(total >= c){
				result = Math.min(result, mid);
				end = mid - 1;
			}
		}
		out.println(result);

		out.close();
	}

	public static int dist(int index, String line) {
		int mul = 1;
		int result = 0;
		for (int i = index; i < line.length(); i++) {
			if (line.charAt(i) == 'T') {
				mul *= -1;
			} else {
				result += mul;
			}
		}
		return result;
	}

	static class Name implements Comparable<Name> {
		String name;
		int h;

		public Name(String name, int h) {
			super();
			this.name = name;
			this.h = h;
		}

		public int compareTo(Name o) {

			return h - o.h;
		}

	}

	static int find(int index, int[] u) {
		if (u[index] != index) {
			return u[index] = find(u[index], u);
		}
		return index;
	}

	static int crossProduct(Point a, Point b) {
		return a.x * b.y + a.y * b.x;
	}

	static long squareDist(Point a) {
		long x = a.x;
		long y = a.y;
		return x * x + y * y;
	}

	static Point minus(Point a, Point b) {
		return new Point(a.x - b.x, a.y - b.y);
	}

	public static boolean nextPer(int[] data) {
		int i = data.length - 1;
		while (i > 0 && data[i] < data[i - 1]) {
			i--;
		}
		if (i == 0) {
			return false;
		}
		int j = data.length - 1;
		while (data[j] < data[i - 1]) {
			j--;
		}
		int temp = data[i - 1];
		data[i - 1] = data[j];
		data[j] = temp;
		Arrays.sort(data, i, data.length);
		return true;
	}

	static class Point {
		int x, y;

		public Point(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}

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

	}

	static class Entry implements Comparable<Entry> {
		int x, cost;

		public Entry(int x, int cost) {
			super();
			this.x = x;
			this.cost = cost;
		}

		public int compareTo(Entry o) {
			// TODO Auto-generated method stub
			if (cost > o.cost) {
				return 1;
			} else if (cost == o.cost) {
				return -1;
			}

			return 0;
		}
	}

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

	static class Scanner {

		BufferedReader br;
		StringTokenizer st;

		public Scanner() throws FileNotFoundException {
			// System.setOut(new PrintStream(new
			// BufferedOutputStream(System.out), true));
			br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File("B-large.in"))));
		}

		public String next() {

			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			return st.nextToken();
		}

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

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

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

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

		public boolean endLine() {
			try {
				String next = br.readLine();
				while (next != null && next.trim().isEmpty()) {
					next = br.readLine();
				}
				if (next == null) {
					return true;
				}
				st = new StringTokenizer(next);
				return st.hasMoreTokens();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}
	}
}


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

/**
 * @author pvasilyev
 * @since 8/11/13
 */
public class ProblemD {

    private static final long MOD = 1000 * 1000 * 1000 + 7;

    public static final String FILE_IN = "std.in";
    public static final String FILE_OUT = "std.out";
    private static boolean debugMode = true;
    private static long[] FACT = new long[20001];

    static {
        long m = 1;
        FACT[0] = 1;
        for (int k = 1; k < FACT.length; ++k) {
            m = (m * k) % MOD;
            FACT[k] = m;
        }
    }

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

        final Scanner reader = new Scanner((debugMode ? System.in : new FileInputStream(FILE_IN)));
        final PrintWriter writer = new PrintWriter(debugMode ? System.out : new FileOutputStream(FILE_OUT));

        solveTheProblem(reader, writer);

        reader.close();
        writer.close();
    }

    private static void solveTheProblem(final Scanner reader, final PrintWriter writer) throws IOException {
        final int n = reader.nextInt();
        final int m = reader.nextInt();
        final int g = reader.nextInt();

        long sum = 0;

        if (n == 0) {
            if (g == 0) {
                writer.println("1");
            } else {
                writer.println("0");
            }
        } else if (m == 0) {
            if (g == 1 && n % 2 == 0) {
                writer.println("1");
            } else if (g == 0 && n % 2 == 1) {
                writer.println("1");
            } else {
                writer.println("0");
            }
        } else {
            for (int k = 0; k <= n; k++) {
                final int n1 = n + m - k - 1;
                if (n1 > 0) {
                    if (k % 2 == g) {
                        sum = (sum + C(n1, m - 1)) % MOD;
                    }
                } else {
                    if (k % 2 != g) {
                        sum = (sum + C(n1, m - 1)) % MOD;
                    }
                }
            }
            writer.println(sum);
        }

    }

    private static long C(final int n, final int k) {
        final long temp = (FACT[n - k] * FACT[k]) % MOD;
        return (FACT[n] * inv(temp, MOD)) % MOD;
    }

     static long inv(long value, final long mod) {
        long pow = mod - 2;

        long exp = value;
        value = quickPow(exp, pow, mod);
        return value % mod;
    }

    private static long quickPow(final long exp, final long pow, final long mod) {
        if (pow == 0) {
            return 1;
        } else if (pow == 1) {
            return exp;
        } else if (pow % 2 == 0) {
            long tmp = quickPow(exp, pow / 2, mod);
            return (tmp * tmp) % mod;
        } else {
            long tmp = quickPow(exp, pow / 2, mod);
            tmp = (tmp * tmp) % mod;
            return (tmp * exp) % mod;
        }
    }

}