package round478;

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main22 {
    public static long mas[] = new long[14];
    public static long ms[] = new long[14];

    public static void main(String[] args) {

        Main22.FastScanner sc = new Main22.FastScanner();

        for (int i = 0;i<14;++i) {
            mas[i] = sc.nextInt();
        }
        reset();
        long res = 0;
        for (int i = 0;i<14;++i) {
            if (mas[i]>0) {
//                int[] ms = Arrays.copyOf(mas, mas.length);
                move(i);
                long res1 = count();
                if (res1>res) res = res1;
                reset();
            }
        }

        System.out.println(res);

    }

    public static void reset() {
        ms = Arrays.copyOf(mas, mas.length);
    }

    public static void move(int n) {
        long k = ms[n];
        ms[n] = 0;
        long sum = k / 14;
        k %= 14;
        for (int i=0;i<14;++i) {
            ms[i] += sum;
        }
        n = (n+1)%14;
        while (k > 0) {
            ms[n]++;
            n = (n+1)%14;
            k--;
        }
    }

    public static long count() {
        long res = 0;
        for (int i =0;i<14;++i) {
            if (ms[i]%2 == 0) res += ms[i];
        }
        return res;
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(String s) {
            try {
                br = new BufferedReader(new FileReader(s));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

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

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

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


/*
 * Author: Minho Kim (ISKU)
 * Date: May 1, 2018
 * E-mail: minho.kim093@gmail.com
 *
 * https://github.com/ISKU/Algorithm
 * http://codeforces.com/problemset/problem/975/B
 */

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

public class B {
	public static void main(String... args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st = new StringTokenizer(br.readLine());

		long[] array = new long[14];
		for (int i = 0; i < 14; i++)
			array[i] = Long.parseLong(st.nextToken());

		long answer = 0;
		for (int i = 0; i < 14; i++) {
			if (array[i] == 0)
				continue;

			long[] temp = new long[14];
			for (int j = 0; j < 14; j++)
				temp[j] = array[j];

			long plus = temp[i] / 14;
			long remain = temp[i] % 14;

			long count = 0;
			for (int k = i + 1; count < 14; count++, k = (k + 1) % 14)
				temp[k] += plus;

			count = remain;
			for (int k = i + 1; count > 0; count--, k = (k + 1) % 14)
				temp[k]++;

			long sum = 0;
			for (int k = 0; k < 14; k++) {
				if (temp[k] % 2 == 0)
					sum += temp[k];
			}

			answer = Math.max(answer, sum);
		}

		System.out.print(answer);
	}
}


package round478;

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main2 {

    public static void main(String[] args) {

        Main.FastScanner sc = new Main.FastScanner();
        int mas[] = new int[14];
        for (int i = 0;i<14;++i) {
            mas[i] = sc.nextInt();
        }
        int res = 0;
        for (int i = 0;i<14;++i) {
            if (mas[i]>0) {
//                int ms[] = new int[14];
                int[] ms = Arrays.copyOf(mas, mas.length);
                int res1 = count(ms, i);
                for (int j = 0;j<14;++j) {
//                    System.out.print(mas[j]+" ");
                }
//                System.out.println();
                if (res1>res) res = res1;
            }
        }

        System.out.println(res);

    }

    public static int count(int[] ms, int n) {
//        System.out.println(n+" "+ms[n]);
        int res = 0;
        int k = ms[n];
        ms[n] = 0;
        for (int i=k;i>0;--i) {
            if (n<13) {n++;}
            else {
                n=0;
            }
            ms[n]++;
//            System.out.println(n + " " + mas[n]);
        }

        for (int i=0;i<ms.length;++i) {
            if (ms[i]!=0) {
                if (ms[i]%2 == 0) res += ms[i];
            }
        }
//        System.out.println(res);
        return res;
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(String s) {
            try {
                br = new BufferedReader(new FileReader(s));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

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

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

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Locale;

public class b
{
    private static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    static String readln() throws IOException
    {
        String line = input.readLine();
        return line;
    }

    public static void main(String[] args) throws IOException
    {
        Locale.setDefault(Locale.US);
        String input = a.readln();
        String[] entries = input.split("\\s+");

        long[] board = new long[entries.length];
        for(int i = 0; i < entries.length; i++) {
            long f = Long.parseLong(entries[i]);
            board[i] = f;
        }

        //bruteforce
        long maxScore = 0;
        for(int i = 0; i < board.length; i++){
            // distribute
            if(board[i] <= 0){
                continue;
            }
            long[] boardCopy = Arrays.copyOf(board, board.length);
            long toMove = boardCopy[i];
            long eachStep = toMove/14;
            long remainder = toMove % 14;

            for(int j = 0; j < 14; j++){
                boardCopy[j] += eachStep;
            }
            for(int j = 1; j <= remainder; j++){
                boardCopy[(j + i) % 14] += 1;
            }

            // calculate score
            long currScore = 0;
            for(int j = 0; j < 14; j++){
                if(boardCopy[j] % 2 == 0){
                    currScore += boardCopy[j];
                }
            }

            maxScore = Math.max(currScore, maxScore);
        }

        System.out.println(maxScore);
    }

}


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

import javax.mail.search.FromStringTerm;

public class Main
	{
	public static void main(String args[]) throws IOException
		{
		BufferedReader c=new BufferedReader(new InputStreamReader(System.in));
		char A[]=c.readLine().toCharArray();
		int pos=10;
		long fact=1;
		for(int i=0;i<=9;i++)
			{
			if(contains(A,(char)('A'+i)))
				{
				fact=fact*pos;
				pos--;
				}
			}
		if(A[0]>='A'&&A[0]<='J')
			fact=(fact*9)/10;

		int numQ=0;
		for(int i=0;i<A.length;i++)
			{
			if(A[i]=='?')
				numQ++;
			}
		BigInteger pow10;
		if(A[0]=='?')
			pow10=new BigInteger("10").pow(numQ-1).multiply(new BigInteger("9"));
		else
			pow10=new BigInteger("10").pow(numQ);
		BigInteger fac=new BigInteger(""+fact);
		BigInteger ans=fac.multiply(pow10);
		System.out.println(ans.toString());
		}

	private static boolean contains(char[] a,char c)
		{
		for(int i=0;i<a.length;i++)
			{
			if(a[i]==c)
				return true;
			}
		return false;
		}
	}

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

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

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

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

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

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

	public char readCharacter()
		{
		int c=read();
		while (isSpaceChar(c))
			c=read();
		return (char) c;
		}

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


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

public class A {
    public static void main(String[] args) {
        BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
        String s;
        int sum = 0;
        try {
            s = bi.readLine();
                //for (String numStr: line.split("\\s"))
            //sum += Integer.parseInt(line);
        }
        catch (Exception t) {

        }
        int cntQ = 0;
        for (int i = 0; i < s.length(); i++)
            if (s.charAt(i) == '?')
                cntQ++;
        boolean[] use = new boolean[26];
        for (int i = 0; i < 26; i++)
            use[i] = false;

        for (int i = 0; i < s.length(); i++)
            if ('A' <= s.charAt(i) && s.charAt(i) <= 'Z') {
                int pos = s.charAt(i) - 'A';
                use[pos] = true;
            }
        int cntL = 0;
        for (int i = 0; i < 26; i++)
            if (use[i])
                cntL++;
        BigInteger ans = new BigInteger("1");
        for (int i = 0; i < cntQ; i++) {
            ans = ans.multiply(new BigInteger("10"));
        }
        for (int i = 0; i < cntL; i++) {
            Integer tmp = new Integer(10 - i);
            ans = ans.multiply(new BigInteger(tmp.toString()));
        }
        if ('1' <= s.charAt(0) && s.charAt(0) <= '9') {

        }
        else {
            ans = ans.divide(new BigInteger("10"));
            ans = ans.multiply(new BigInteger("9"));
        }
        System.out.println(ans.toString());
    }
}


//import java.util.*;
public class Main{
    public static void main(String[]args){
        Scanner input = new Scanner(System.in);
        String s = input.next();
        int an=0,x=11,xx=0;
        boolean a[]=new boolean[10];
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i)=='?')
                an++;
            else if('A'<=s.charAt(i)&&s.charAt(i)<='J'&& !a[s.charAt(i)-'A']){
                a[s.charAt(i)-'A'] = true;
                xx++;x--;
            }
        }
      //  System.out.println(xx+" "+x+" "+an);
        System.out.println((int)Math.pow(x,xx)*(int)Math.pow(10,an));
    }
}


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

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

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

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

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

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

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

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

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

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

public class OutputWriter {
	private final PrintWriter writer;

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

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

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

	public void println(Object... objects) {
		print(objects);
		writer.println();
	}

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

}

public class candle
	{
public static void main(String args[]) throws IOException
		{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastReader in = new FastReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		double r ;
		String s = in.next();
		int a[] = new int[11];
		char c[] = s.toCharArray();
		int result = 1;
		int m = 10;
		if('0'<=c[0] && c[0]<='9')
			{
			for(int i=1;i<c.length;i++)
				{
				if('A'<=c[i] && c[i]<='J')
					{
					a[c[i]-64]++;
					if(a[c[i]-64] == 1)
						{
						result = result*m;
						m--;
						}
					}
				else if(c[i] == '?')
					result = 10*result;
				}

			}
		else if(c[0] == '?')
			{
			result = 9;
			for(int i=1;i<c.length;i++)
				{
				if(c[i] == '?')
					result = result*10;
				else if('A' <= c[i] && c[i]<= 'J')
					{
					a[c[i]-64]++;
					if(a[c[i]-64] == 1)
						{
						result = result*m;
						m--;
						}
					}
				}
			}
		else
			{
			result = 9;
			m = 9;
			for(int i=1;i<c.length;i++)
				{
				if(c[i] == '?')
					result = result*10;
				else if('A' <= c[i] && c[i]<= 'J')
					{
					a[c[i]-64]++;
					if(a[c[i]-64] == 1)
						{
						result = result*m;
						m--;
						}
					}

				}
			}
	        out.println(result);

					out.close();

		}
	}


public class sick {

	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		String a =input.next();
		String b=input.next();
		StringBuilder sb=new StringBuilder(b);

	if(a.equals(sb.reverse().toString())){
		System.out.println("YES");
	}
	else {
		System.out.println("NO");
	}

}
}


import java.util.*;
import java.io.*;
public class Translation
{
    public static void main(String[] args)
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String s=br.readLine();
        String s1=s.reverse();
        if(s.equals(s1))
        System.out.println("YES");
        else
        System.out.println("NO");
    }
}


import java.util.*;
import java.lang.*;
import java.io.*;
public class MyClass {
    public static void main(String args[]) {
       Scanner sc=new Scanner(System.in);
       String s=sc.nextLine();
       String s1=sc.nextLine();
       StringBuilder input1 = new StringBuilder();

       input1.append(s1);

        // reverse StringBuilder input1
        input1 = input1.reverse();
     //   System.out.println(input1);
       if(s.equals(input1.toString()))
       {
           System.out.println("YES");
       }
       else
       {
           System.out.println("NO");
       }
}
}
           System.out.println("NO");
       }
}
}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        for (int i = 0; i < num; i++) {
            String str = in.next();
`
            int m = str.length() / 2;
            boolean flag = true;
            for (int j = 0, z = str.length() - 1; j < m && z > m; j++, z--) {
                if(str.charAt(z) != str.charAt(j))
                    flag = false;
            }
            if(flag)
                System.out.println(true);
            else
                System.out.println(false);

        }

    }
}


public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        System.out.println(calcular(s));
    }

    public static String calcular(String s){
        String resp = "NO";
        s = "00" + s;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + 1; j < s.length(); j++) {
                for (int k = j + 1; k < s.length(); k++) {
                    int x = 100 * (s.charAt(i) - '0') + 10 * (s.charAt(j) - '0') + s.charAt(k) - '0';
                    if (x % 8 == 0) {
                        resp = "YES\n" + x;
                    }
                }
            }
        }
        return resp;
    }
}


public class Main {
    private static void checkNum(String num)
    {
        int intNum = -1;
        String temp = "";
        if (num.length() > 100)
            return;

if(num.length()>3) {
            //System.out.println(num.substring(num.length() - 3, num.length()));
            if(num.substring(num.length() - 3, num.length()) == "000")
            {
                System.out.println("YES " + num);
            }
            for(int i = num.length()-1;i>=num.length()/2;i--)
            {
                for(int j = i-1;j>=1;j--)
                {
                    for(int k = j-1;k>=0;k--)
                    {

                        //temp = "" + num.charAt(k) + num.charAt(j) + num.charAt(i); //num.substring(k,j) + num.substring(j,i) + num.substring()
                        temp = num.substring(k,j) + num.substring(i);
                        if(Integer.parseInt(temp) % 8 == 0)
                            intNum = Integer.parseInt(temp);
                        //System.out.println("" + k + j + i);
                    }
                }
            }

        }
        intNum = Integer.parseInt(num);
        if(intNum%8 == 0)
        System.out.println("YES\n" + intNum);
        else
            System.out.println("NO");
}


public class Main {
    private static String checkNum(int num)
    {
       if (344%8 == 0)
       return "YES\n" + 344;
    }
}


import java.io.*;
import java.util.*;
import java.lang.*;
public class Main{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        String s=sc.next();
        for(int i=0;i<s.length();i++){
            if(s[i]=='0'){
                continue;
            }
            for(int j=i+1;j<s.length();j++){
                for(int k=j+1;k<s.length();k++){
                    int cur=(s[i]-'0')*100+(s[j]-'0')*10+(s[k]-'0');
                    if(curr%8==0){
                        System.out.println("YES");
                        System.out.println(curr);
                        return;
                    }
                }
            }
        }

        for(int i=0;i<s.length();i++){
            if(s[i]=='0'){
                continue;
            }
            for(int j=i+1;j<s.length();j++){
                int curr=(s[i]-'0')*10+(s[j]-'0');
                if(curr%8==0){
                    System.out.println("YES");
                    System.out.pritln(curr);
                    return;
                }
            }
        }

        for(int i=0;i<s.length();i++){
            int curr=s[i]-'0';
            if(curr%8==0){
                System.out.println("YES");
                System.out.println(curr);
                return;
            }
        }

        System.out.println("NO");
        return ;
    }
}


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

public class Contest {

	public static boolean isValid(int x, int k, int n) {
		int sum = x;
		while (x > 0) {
			sum += x / k;
			x /= k;
		}
		return sum >= n;
	}

	public static int binarySearch(int n, int k) {
		int lo = 1;
		int hi = n;
		int res = 0;
		while (lo <= hi) {
			int mid = (lo + hi) / 2;
			if (isValid(mid, k, n)) {
				hi = mid - 1;
				res = mid;
			} else {
				lo = mid + 1;
			}
		}
		return res;
	}

	public static void main(String[] args) throws IOException, NumberFormatException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int k = Integer.parseInt(st.nextToken());
		System.out.println(binarySearch(n, k));
	}
}


import java.util.Scanner;
import java.lang.Math;

public class Solution {

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

        int exp = 0;
        int value = 1;
        int v = 1;

        while (value != 0) {
            value = v / Math.pow(k, exp);
            v++;
            exp++;
        }

        System.out.print(v);
    }
}


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

public class BMOil{

    static int n, k;

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

        int lo = 0;
        int hi = 1;

        //upper bound for hi
        while(!works(hi)) {
           hi *= 2;
        }

        while(hi - lo > 1) {
            int mid = lo + (hi - lo) / 2;
            if(works(mid))
        	    hi = mid;
            else
        	    lo = mid;
        }
    }

    static bool works(int mid) {
        int lines = mid; // number of lines Vasya can write
        int lines_left = n; //starts after writing once
        for (int i=0; lines > 0; i++){
            lines_left -= lines/ (Math.pow(k,i);
            if (lines_left <= 0)
                return true;
        }
        return false;
    }
}


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

public class Main{
    public static boolean burnOil(int v, int k, int n)
    {
        int total = v;
        int temp = v;
        while(total < n && temp != 0)
        {
            temp /= k;
            total += temp;
        }
        if(total >= n)
            return true;
        return false;
    }
    public static void main(String[] args) {
      // Use the Scanner class
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int k = sc.nextInt();
      int low = 0;
      int high = n;
      while(low < high)
      {
        int mid = (low + high) / 2;
        if(burnOil(mid, k, n))
            high = mid - 1;
        else
            low = mid + 1;
      }
      if(burnOil(low, k, n)
        System.out.println(low);
      else
        System.out.println(low+1);
      /*
      int n      = sc.nextInt();        // read input as integer
      long k     = sc.nextLong();       // read input as long
      double d   = sc.nextDouble();     // read input as double
      String str = sc.next();           // read input as String
      String s   = sc.nextLine();       // read whole line as String
      */
    }
}


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

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int d = sc.nextInt();
        int sum1 = Math.max(((3*a)/10),((a)-(a/250))*(c));
        int sum1 = Math.max(((3*b)/10),((b)-(b/250))*(d));

        if(sum1>sum2) {
            System.out.println("Misha");
        }
        else if (sum1 == sum2) {
            System.out.println("Vasya");
        }
        else {
            System.out.println("Tied");
        }
    }
}


import java.util.*;
public class Main{
    public static void main(String args[]){
        Scanner s=new Scanner(System.in);
        int a = s.nextInt();
        int b = s.nextInt();
        int c = s.nextInt();
        int d = s.nextInt();
        int resultA = Math.max(3*a /10 , a-a/250*c);
        int resultB = Math.max(3*b/10 , b-b/250*d);
        if(resultA<resultB){
            System.out.println("Vasya");
        }else if(resultA>resultB)){
            System.out.println("Misha");
        }else{
            System.out.println("Tie");
        }
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.InputMismatchException;
import java.util.Random;

public class CF_501A {
	static FastScanner sc = new FastScanner(System.in);
	static PrintWriter out = new PrintWriter(System.out);

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

	public void run(){
		int a = sc.nextInt();
		int b = sc.nextInt();
		int c = sc.nextInt();
		int d = sc.nextInt();
		int aa = Math.max(3*a/10, a-(a/250)*c);
		int bb = Math.max(3*b/10, b-(b/250)*d);
		if(aa>bb)
			out.println("Misha");
		else if(bb>aa)
			out.println("Vasya");
		else
			out.println("Tie");
	}

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

	    public FastScanner(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 boolean isSpaceChar(int c) {
		      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}
}


import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner input = new Scanner (System.in);
            int a = input.nextInt();
            int b = input.nextInt();
            int c = input.nextInt();
            int d = input.nextInt();
            double m = max(a,c);
            double v = max(b,d);
            if(m==v){
                System.out.println("Tie");
                }
            else if(m>v){
                    System.out.println("Misha");
                }
            else{

                System.out.println("Vasya");

                }
        }
        public static double max(int p , int t){
            double max = Math.max(((3*p)/10),(p-(p/250)*t));
            }
    }


package codeforcesNumbertheorypractice;

import FastIO.InputReader;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

public class TaskI {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        Arrays.sort(arr);
        int flag = 0;
        for (int i = 1; i < n - 1; i++) {
            int x = arr[i - 1];
            int y = arr[i];
            int z = arr[i + 1];

            int s = (x + y + z) / 2;
            if (s > z) {
                flag = 1;
                break;
            }
        }
        if (flag == 1) {
            out.println("YES");
        } else {
            out.println("NO");
        }

    }

}


package codeforcesNumbertheorypractice;

import FastIO.InputReader;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

public class TaskI {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        Arrays.sort(arr);
        int flag = 0;
        for (int i = 1; i < n - 1; i++) {
            double x = arr[i - 1];
            double y = arr[i];
            double z = arr[i + 1];

            double s = (x + y + z) / 2;
            if (s > z) {
                flag = 1;
                break;
            }
        }
        if (flag == 1) {
            out.println("YES");
        } else {
            out.println("NO");
        }

    }

}


public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		int[] arr = new int[t];
		for(int i=0;i<t;i++){
			arr[i]=sc.nextInt();
		}
		Arrays.sort(arr);
		if(arr[t-1]>(arr[0]+arr[1])){
			System.out.println("YES");
		}else{
			System.out.println("NO");
		}
	}

}


public class CodeForce02 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc= new Scanner(System.in);
        int n = sc.nextInt();

        int[] a=  new int[n];

        for (int i = 0; i < n; i++) a[i] = sc.nextInt();
        Arrays.sort(a);
        for (int i = 0; i < n-2; i++)
        if (a[i]+a[i+1] > a[i+2]) {
            System.out.println("YES");
            return;
        }

        System.out.println("NO");
    }

}


import java.util.Scanner;

public class frGm{
	public static int main(){
		int[] num = new int[110];
		int n;
		Scanner scan = new Scanner(System.in);
		n = scan.nextInt();
		while(n!=0){
			int a;
			a = scan.nextInt();
			num[a]++;
			n--;
		}
		int cnt=0;
		int a=0,b=0;
		for(int i=1;i<=100;i++){
			if(num[i]!=0){
				cnt++;
				if(a==0) a=i;
				else b=i;
			}
		}
		if(cnt!=2){
			System.out.println("NO");
		}else{
			if(num[a]==num[b]){
				System.out.println("YES");
				System.out.println(a + " " + b);
			}
			else{
				System.out.println("NO");
			}
		}
	}
}


//1.8.0_111(rextester.com)1.8.0_131(codeforces.com)2018-01-04
import java.util.Scanner;
public class a{
    public static void main(String args[]){
        Scanner scan=new Scanner(System.in);
        int cards=scan.nextInt(),totalInt=0;
        int checkFair[]=new int[101],n[]=new int[100];
        for(int i=0;i<cards;i++){
            int sequence=scan.nextInt();
            if(++checkFair[sequence]==1)n[totalInt++]=sequence;
        }
        if(totalInt==2&&checkFair[num[0]]==checkFair[num[1]])
            System.out.print("YES\n"+n[0]+" "+n[1]);
        else System.out.print("NO");
    }
}


 public class Solution{
 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int size = in.nextInt();

        int[] counts = new int[99];
        for (int i = 0; i < size; i++) {
            counts[in.nextInt()]++;
        }

        int index1 = 0;
        int index2 = 0;
        for (int i = 0; i < counts.length; i++) {
            if (counts[i] != 0 && counts[i] % 2 == 0) {
                if (index1 == 0)
                    index1 = i;
                else if (index2 == 0)
                    index2 = i;
            }

        }
        if (index1 != 0 && index2 != 0) {
            System.out.println("YES");
            System.out.println(index1 + " " + index2);
        } else
            System.out.println("NO");

        in.close();
    }
 }


import java.util.*;
public class JavaApplication41 {
    public static void main(String[] args) {
 Scanner st =new Scanner(System.in);
    int y=st.nextInt();
    int b=st.nextInt(),c=0,d=0,e=1;
    String f="Yes";
for(int i=1;i<y;i++)
{
    int r=st.nextInt();{
    if (c==0&&r!=b){
        c=r;
    d++;}
    if(b!=0&&c!=0&&r!=b&&r!=c)
        f="No";

    if(d==0)
        f="No";

}
}
        System.out.println(f);
        if(f=="Yes")
            System.out.println(b+" "+c);


//package round107;

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

public class D {

	private boolean prime(long n) {
		for (long i = 2; i * i <= n; i++) {
			if (n % i == 0) {
				return false;
			}
		}
		return true;
	}

	private void solve() throws IOException {
		long n = nextLong();
		if (prime(n)) {
			println(1);
			println(0);
			return;
		}

		ArrayList<Long> p = new ArrayList<Long>();
		for (long i = 2; i * i <= n; i++) {
			while (n % i == 0) {
				p.add(i);
				n /= i;
			}
		}

		p.add(n);
		if (p.size() == 2) {
			println(2);
			return;
		}

		println(1);
		println(p.get(0) * p.get(1));
	}

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

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

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

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

	private void print(Object o) {
		writer.print(o);
	}

	private void println(Object o) {
		writer.println(o);
	}

	private void printf(String format, Object... o) {
		writer.printf(format, o);
	}

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

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	private void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(13);
		}
	}
}


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

public class A implements Runnable {
    private MyScanner in;
    private PrintWriter out;

    private boolean prime(long n) {
        if (n < 2) {
            return false;
        }
        for (int i = 2; (long) (i) * i <= n; ++i) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    private void solve() {
        long q = in.nextLong();
        ArrayList<Long> div = new ArrayList<Long>();
        for (int i = 2; (long) (i) * i <= q; ++i) {
            if (q % i == 0) {
                if (prime(i)) {
                    div.add((long) i);
                }
                if ((long) (i) * i != q && prime(q / i)) {
                    div.add(q / i);
                }
            }
        }
        if (div.size() == 0) {
            out.println(1);
            out.println(0);
            return;
        }
        if (div.size() == 1) {
            out.println(2);
            return;
        }
        Collections.sort(div);
        if (div.size() == 2 && div.get(0) * div.get(1) == q) {
            out.println(2);
            return;
        }
        out.println(1);
        out.println(div.get(0) * div.get(1));
    }

    @Override
    public void run() {
        in = new MyScanner();
        out = new PrintWriter(System.out);
        solve();
        in.close();
        out.close();
    }

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

    static class MyScanner {
        private BufferedReader br;
        private StringTokenizer st;

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

        public void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

        public String nextLine() {
            try {
                st = null;
                return br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        public String next() {
            return 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.*;
import java.util.*;

public class WinOrFreeze {

	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		long q = Long.parseLong(in.readLine());
		int cnt = 0;
		long res = 1;
		for (long i = 2; i*i <= q; i++) {
			if (q%i == 0) {
				if (cnt <= 1) {
					res *= i;
				}
				cnt++;
			}
		}
		if (cnt == 0) {
			System.out.println(1);
			System.out.println(0);
		} else if (cnt > 1) {
			System.out.println(1);
			System.out.println(res);
		} else {
			System.out.println(2);
		}
	}
}


import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class A {

    // SieveOfEratosthenes
    public static class Prime { // {{{
        public static final int LIMIT = (int) Math.sqrt(1e13);
        public static BitSet prime;
        public static List<Integer> list; // list contains the primes less than or equal to LIMIT

        static {
            int halfLimit = LIMIT>>1;
            int sqrtLimit = (int) Math.sqrt(LIMIT);

            prime = new BitSet(halfLimit);
            prime.set(0, prime.size(), true);

            prime.clear(0);
            for (int num=3; num<=sqrtLimit; num+=2)
                if (prime.get(num>>1))
                    for (int factor = num*num, inc = num << 1; factor <= LIMIT; factor += inc)
                        prime.clear(factor>>1);

            list = new ArrayList<Integer>();
            list.add(2);
            for (int i = 1; i < halfLimit; i++)
                if (prime.get(i))
                    list.add((i << 1) + 1);
        }
        // num must less than or equal to LIMIT^2
        public static boolean isPrime(int num) {
            if (num<2) return false;
            if ((num & 1) == 0)
                return num==2;

            if (num <= LIMIT)
                return prime.get(num>>1);

            int max = (int) Math.sqrt(num);
            for (int p : list) {
                if (p > max)
                    break;
                if (num % p == 0)
                    return false;
            }
            return true;
        }
    } // }}}

    public A() throws Exception {
        long q = in.nextLong();
        int n = 0;
        int first = 1;
        for (int p:Prime.list) {
            if (q==1) break;
            while (q%p==0) {
                q /= p;
                n++;
                if (n==3) break;
                first *= p;
            }
            if (n==3) break;
        }

        if (n==2)
            System.out.println(2);
        else if(n<2)
            System.out.println("1\n0");
        else
            System.out.println("1\n"+first);

        System.out.print(buf);
    }

    Scanner in = new Scanner(System.in);
    StringBuilder buf = new StringBuilder();
    public static void main(String[] args) throws Exception { // {{{
        new A();
    } // }}}
    public static void debug(Object... arr) { // {{{
        System.err.println(Arrays.deepToString(arr));
    } // }}}
}


import java.util.Scanner;

public class LastDigit{

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		int n = scan.nextInt();

	 	int number = 8;
		unsigned long resultNumber = 1378;

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

			resultNumber = resultNumber * number;

		}

		System.out.println(resultNumber % 10);

	}

}


package problema;

import java.util.Scanner;
public class Test {

    public static void main(String[] args) {
        int x;
        long n;
        long dup = 1;
        Scanner s = new Scanner(System.in);
        n = s.nextInt();
        for(int i=1;i<n;i++){
            dup*= 1378;
        }
        x = dup%10;
        System.out.println(x);
    }

}


import java.util.*;
import java.lang.*;
import java.io.*;
public class main
{
	public static void main (String[] args) throws java.lang.Exception
	{

      Scanner sc = new Scanner (System.in);
        long a = sc.nextLong();
        if(a==0)System.out,prinln("0");
        else{
        if(a%4==0)System.out.println("6");
        if(a%4==1)System.out.println("8");
        if(a%4==2)System.out.println("4");
        if(a%4==3)System.out.println("2");
        }
        }
	}


import java.util.Scanner;
public class JavaApplication26 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int n=input.nextInt();
        int l= Math.pow(1378,n);
        System.out.println(l%10);
    }

}


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

public class LuckyCommonSubsequence {
	static char s1[];
	static char s2[];
	static char[] virus;
	static StringBuilder dp[][][];
	static int dp_LCS[][][];
	static int INF = 1000000000;
	static int[] fail;
	static PrintWriter out;
	static StringBuilder ans;

	static int LCS(int i, int j, int prefixMatched) {
		if(prefixMatched >= virus.length) {
			return INF * -1;
		}
		if(i >= s1.length || j >= s2.length) {
			return 0;
		}
		if(dp_LCS[i][j][prefixMatched] != -1) {
			return dp_LCS[i][j][prefixMatched];
		}
		int res = -1;
		int res1 = -1;
		int prefixMatched2 = prefixMatched;
		while (prefixMatched2 >= 0 && s1[i] != virus[prefixMatched2])
			prefixMatched2 = fail[prefixMatched2];
		prefixMatched2++;
		res1 =  LCS(i+1,  j+1, prefixMatched);
		if(s1[i] == s2[j]) {
			res = LCS(i+1,  j+1, prefixMatched2) + 1;
		}
		return dp_LCS[i][j][prefixMatched] = Math.max(res1,
				Math.max(res, Math.max(LCS(i+1, j, prefixMatched), LCS(i, j+1, prefixMatched))));
	}
	static void LCSPrint(int i, int j, int prefixMatched) {
		if(i >= s1.length || j >= s2.length) {
			return;
		}
//		if(prefixMatched >= virus.length) {
//
//		}
		int prefixMatched2 = prefixMatched;
		while (prefixMatched2 >= 0 && s1[i] != virus[prefixMatched2])
			prefixMatched2 = fail[prefixMatched2];
		prefixMatched2++;
		int optimal = LCS(i, j, prefixMatched);
		int sol1 = LCS(i + 1, j + 1, prefixMatched2) + 1;
		int sol4 = LCS(i+1, j+1, prefixMatched);
		int sol2 = LCS(i + 1, j, prefixMatched);
		int sol3 = LCS(i, j + 1, prefixMatched);
		if(optimal == sol4) {
			LCSPrint(i+1, j+1, prefixMatched2);
		} else
			try{

			if(optimal == sol2) {
			LCSPrint(i + 1, j, prefixMatched);
		} else
			if(optimal == sol1) {
				ans.append(s1[i]);
				LCSPrint(i+1, j+1, prefixMatched2);
		}else LCSPrint(i, j+1, prefixMatched);
		}catch(Exception e) {
			out.println("eh");
		}
	}
	public static int[] FailFunction2(String s) {
		int n = s.length();
		int F[] = new int[n + 1];
		int i = 0, j = -1;
		F[i] = j;
		while (i < n) {
			while (j >= 0 && s.charAt(i) != s.charAt(j))
				j = F[j];
			i++;
			j++;
			F[i] = j;
		}
		return F;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		s1 = bf.readLine().toCharArray();
		s2 = bf.readLine().toCharArray();
		virus = bf.readLine().toCharArray();
		out = new PrintWriter(System.out);
		ans = new StringBuilder("");
		dp_LCS = new int[s1.length+1][s2.length+1][virus.length+1];
		for(int i = 0; i< dp_LCS.length; i++) {
			for(int j = 0; j < dp_LCS[i].length; j++) {
				Arrays.fill(dp_LCS[i][j], -1);
			}
		}
		fail = FailFunction2(new String(virus));

		LCSPrint(0, 0, 0);

//		out.println(LCS(0, 0, 0));
		if(ans.toString().length() == 0){
			out.println('0');
		} else {
			out.println(ans.toString());
		}
		out.flush();
		out.close();

	}
}


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

public class LuckyCommonSubsequence {
	static char s1[];
	static char s2[];
	static char[] virus;
	static StringBuilder dp[][][];
	static int dp_LCS[][][];
	static int INF = 1000000000;
	static int[] fail;
	static PrintWriter out;
	static StringBuilder ans;

	static int LCS(int i, int j, int prefixMatched) {
		if(prefixMatched >= virus.length) {
			return INF * -1;
		}
		if(i >= s1.length || j >= s2.length) {
			return 0;
		}
		if(dp_LCS[i][j][prefixMatched] != -1) {
			return dp_LCS[i][j][prefixMatched];
		}
		int res = -1;
		int res1 = -1;
		int prefixMatched2 = prefixMatched;
		while (prefixMatched2 >= 0 && s1[i] != virus[prefixMatched2])
			prefixMatched2 = fail[prefixMatched2];
		prefixMatched2++;
		res1 =  LCS(i+1,  j+1, prefixMatched);
		if(s1[i] == s2[j]) {
			res = LCS(i+1,  j+1, prefixMatched2) + 1;
		}
		return dp_LCS[i][j][prefixMatched] = Math.max(res1,
				Math.max(res, Math.max(LCS(i+1, j, prefixMatched), LCS(i, j+1, prefixMatched))));
	}
	static void LCSPrint(int i, int j, int prefixMatched) {
		if(i >= s1.length || j >= s2.length) {
			return;
		}
		if(prefixMatched >= virus.length) {
			out.println("eh");
		}
		int prefixMatched2 = prefixMatched;
		while (prefixMatched2 >= 0 && s1[i] != virus[prefixMatched2])
			prefixMatched2 = fail[prefixMatched2];
		prefixMatched2++;
		int optimal = LCS(i, j, prefixMatched);
		int sol1 = LCS(i + 1, j + 1, prefixMatched2) + 1;
		int sol4 = LCS(i+1, j+1, prefixMatched);
		int sol2 = LCS(i + 1, j, prefixMatched);
		int sol3 = LCS(i, j + 1, prefixMatched);
//		try{
		if(optimal == sol4) {
			LCSPrint(i+1, j+1, prefixMatched2);
		} else if(optimal == sol2) {
			LCSPrint(i + 1, j, prefixMatched);
		} else
			if(optimal == sol1) {
				ans.append(s1[i]);
				LCSPrint(i+1, j+1, prefixMatched2);
		}else LCSPrint(i, j+1, prefixMatched);
//		}catch(Exception e) {
//		}
	}
	public static int[] FailFunction2(String s) {
		int n = s.length();
		int F[] = new int[n + 1];
		int i = 0, j = -1;
		F[i] = j;
		while (i < n) {
			while (j >= 0 && s.charAt(i) != s.charAt(j))
				j = F[j];
			i++;
			j++;
			F[i] = j;
		}
		return F;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		s1 = bf.readLine().toCharArray();
		s2 = bf.readLine().toCharArray();
		virus = bf.readLine().toCharArray();
		out = new PrintWriter(System.out);
		ans = new StringBuilder("");
		dp_LCS = new int[s1.length+1][s2.length+1][virus.length+1];
		for(int i = 0; i< dp_LCS.length; i++) {
			for(int j = 0; j < dp_LCS[i].length; j++) {
				Arrays.fill(dp_LCS[i][j], -1);
			}
		}
		fail = FailFunction2(new String(virus));

		LCSPrint(0, 0, 0);

//		out.println(LCS(0, 0, 0));
		if(ans.toString().length() == 0){
			out.println('0');
		} else {
			out.println(ans.toString());
		}
		out.flush();
		out.close();

	}
}


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

public class D_D2_201 {
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        String s2 = in.nextLine();
        String virus = in.nextLine();
        String ans = lcsReversedWithKMP(s1, s2, virus);
        System.out.println(ans.length() == 0 ? "0" : ans);
    }

    public static int[] buildAutomata(String pat) {
        int M = pat.length();
        int atmataIndx = 0;
        int patIndx = 1;
        int[] automata = new int[M];
        while (patIndx < M) {
            if (pat.charAt(atmataIndx) == pat.charAt(patIndx)) {
                atmataIndx++;
                automata[patIndx] = atmataIndx;
                patIndx++;
            } else {
                if (atmataIndx != 0) {
                    atmataIndx = automata[atmataIndx - 1];
                } else {
                    automata[patIndx] = 0;
                    patIndx++;
                }
            }
        }
        return automata;
    }

    public static boolean KMP(String str, String pat) {
        int[] automata = buildAutomata(pat);
        int M = pat.length();
        int N = str.length();

        int atmataIndx = 0;
        int i = 0;
        while (i < N) {
            if (str.charAt(i) == pat.charAt(atmataIndx)) {
                i++;
                atmataIndx++;
                if (atmataIndx == M) {
                    return true;
                }
            } else if (i < N) {
                if (atmataIndx != 0) {
                    atmataIndx = automata[atmataIndx - 1];
                } else {
                    i++;
                }
            }
        }
        return false;
    }

    public static String lcsReversedWithKMP(String a, String b, String virus) {
        String maxLcs = "";
        int[][] LCS = new int[a.length() + 1][b.length() + 1];
        a = new StringBuilder(a).reverse().toString();
        b = new StringBuilder(b).reverse().toString();
        for (int i = 0; i < a.length(); i++) {
            for (int j = 0; j < b.length(); j++) {
                if (a.charAt(i) == b.charAt(j)) {
                    LCS[i + 1][j + 1] = LCS[i][j] + 1;
                } else {
                    LCS[i + 1][j + 1] = Math.max(LCS[i][j + 1], LCS[i + 1][j]);
                }
            }
        }

        StringBuilder sb = new StringBuilder();

        for (int i = a.length(), j = b.length(); i != 0 && j != 0;) {
            if (a.charAt(i - 1) == b.charAt(j - 1)) {
                boolean matched = KMP(sb.toString() + a.charAt(i - 1), virus);
                if (!matched) {
                    sb.append(a.charAt(i - 1));
                }
                String newA = new StringBuilder(a).deleteCharAt(i - 1).reverse().toString();
                String newB = new StringBuilder(b).deleteCharAt(j - 1).reverse().toString();
                String newLcs = lcsReversedWithKMP(newA, newB, virus);
                if (newLcs.length() > maxLcs.length()) {
                    maxLcs = newLcs;
                }

                i--;
                j--;
            } else if (LCS[i][j] == LCS[i - 1][j]) {
                i--;
            } else if (LCS[i][j] == LCS[i][j - 1]) {
                j--;
            }
        }
        if (sb.length() > maxLcs.length()) {
            return sb.toString();
        }
        return maxLcs;
    }
}


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

public class Main {

	public static class FastReader {
		BufferedReader br;
		StringTokenizer root;

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

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

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

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

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

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

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));

	public static FastReader sc = new FastReader();

	static int mod = (int) (1e9+7),MAX=(int) (2e5);
    static List<Integer>[] edges;
	static char[] vir,s1,s2;
	static int[][][] dp;
	static int[] lps;
	public static void main(String[] args){

	  s1 = sc.next().toCharArray();
	  s2 = sc.next().toCharArray();
	  vir = sc.next().toCharArray();
	  lps = lps(new String(vir));
	  dp = new int[110][110][110];

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

	  int ans = f(0,0,0);
	  if(ans == 0) out.print(0);
	  else print(0,0,0,"");

      out.close();
	}

	private static void print(int i, int j, int k, String str) {
		  if (i == s1.length || j == s2.length) {
		        out.print(str);
		        return;
		    }
		    int cur = dp[i][j][k];
		    int r = f(i+1,j,k);
		    if (r == cur){ print(i+1,j,k,str); return; }
		    r = f(i,j+1,k);
		    if (r == cur) { print(i,j+1,k,str); return; }

		    while (k > 0 && vir[k] != s1[i]) k = lps[k - 1];
		    if (vir[k] == s1[i]) ++k;
		    print(i+1,j+1,k,str+s1[i]);

	}

	static int[] lps(String vir) {
	    int n = vir.length();
	    int[] pi = new int[n];
	    for (int i = 1; i < n; i++) {
	        int j = pi[i-1];
	        while (j > 0 && vir.charAt(i) != vir.charAt(j))
	            j = pi[j-1];
	        if (vir.charAt(i) == vir.charAt(j))
	            j++;
	        pi[i] = j;
	    }
	    return pi;
	}

	private static int f(int i, int j, int k) {
		if (k == vir.length) return -Integer.MIN_VALUE/10;
		if (i == s1.length) return 0;
		if (j == s2.length) return 0;

		if(dp[i][j][k]!=-1) return dp[i][j][k];

		int o1=0,o2=0,o3=0;

		if(s1[i] == s2[j]) {
			if(s1[i] == vir[k]) {
				o1 = 1 + f(i+1,j+1,k+1);
			}else {
				/*
				 * if next char don't match we can't reset k to 0
				 * becz now suffix of lcs = ....prefix of virus + s1[i]
				 * the new k will be length of LPS of string = prefix of virus + s1[i]
				 */
			    while (k > 0 && vir[k] != s1[i]) k = lps[k-1];
			    if (s1[i] == vir[k]) k++;
				o1 = 1 + f(i+1,j+1,k);
			}
		}
		o2 = f(i+1,j,k);
		o3 = f(i,j+1,k);

		return dp[i][j][k] = Math.max(o1, Math.max(o2, o3));
	}

}


//app.は全部けす

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

//流す前にfinalにする
public final class EcRound35CApplication {

	public static void main(String[] args) {

		//実インプット部　appだけけす
		Input input = new Input();
		input = SystemInput();
		Integer result = run(input);
		System.out.print(result);
		//実インプット部ここまで

	}

	//流す前にstaticにする
	private static void tester(Integer no,Integer KFirst,Integer KSecond , Integer KThird,String answer) {
		Input input = new Input();
		input.setInput(KFirst,KSecond,KThird);
		String result = run(input);

		if(result == answer) {
			System.out.println("No." + no + ":OK");
		}
		else {
			System.out.println("No." + no + ":failed");
			System.out.println("result:" + result);
			System.out.println("answer:" + answer);
		}
	}

	//流す前にstaticにする
	private static Input SystemInput() {
		Input input = new Input();
		Scanner sc = new Scanner(System.in);
		Integer first = sc.nextInt();
		Integer second = sc.nextInt();
		Integer third = sc.nextInt();
		input.setInput(first,second,third);
		sc.close();
		return input;
	}

	//流す前にstaticにする
	private static String run(Input input) {
		String result = "NO";

		//どれが1なら議論の余地もなくYES
		if(input.oneCheck()) {
			return "YES";
		}

		//6パターン検証してどっかで引っかかれば良い
		//starter:1秒目に光るやつ
		//follower:次を埋めるやつ
		//matcher:最後に当てはまるか検証するやつ
		//inputを(A,B,Cとして)

		//A,B,C
		result = checker(input.getKFirst(),input.getKSecond(),input.getKThird(),result);
		//A,C,B
		result = checker(input.getKFirst(),input.getKThird(),input.getKSecond(),result);
		//B,A,C
		result = checker(input.getKSecond(),input.getKFirst(),input.getKThird(),result);
		//B,C,A
		result = checker(input.getKSecond(),input.getKThird(),input.getKFirst(),result);
		//C,A,B
		result = checker(input.getKThird(),input.getKFirst(),input.getKSecond(),result);
		//C,B,A
		result = checker(input.getKThird(),input.getKSecond(),input.getKFirst(),result);

		return result;
	}

	private static String checker(Integer starter,Integer follower,Integer matcher,String result) {

		//既にresultがYESになってたら処理を飛ばす
		if(result == "YES") {
			return result;
		}

		//パターン出しのためユークリッド互除法を利用して最小公倍数を出しておく
		Integer LCM = starter*follower/euclidean(starter,follower);

		//遅延秒数管理
		Integer followerDelay;

		//遅延秒数をずらしてどっかでビンゴしないか試す
		for(followerDelay = 0; followerDelay < starter; followerDelay++){
			//最小公倍数+ずれ分足しとけばだいたいパターン網羅できるっしょ的な
			Integer pattarnLength = LCM * 2 + followerDelay;

			//starterとfollowerで光らないやつ数え上げ
			List<Integer> needToMatchList = new ArrayList<Integer>();
			for(Integer pattarn = 1; pattarn <= pattarnLength ; pattarn++) {
				//starterが光るかチェック（starterは1秒目点灯なのでかならず余り1になる）
				if(pattarn % starter == 1) {
					continue;
				}
				//followerが光るかチェック
				//丁度割り切れる場合があるのでfollowerで割った余りを検証に使う
				if(pattarn % follower == (1+followerDelay)%follower) {
					continue;
				}
				//ヒットしなければリストに加える
				needToMatchList.add(pattarn);
			}

			//リストの長さが0ならまずOK
			if(needToMatchList.size() == 0) {
				return "YES";
			}

			//一つだけある場合は、リストにLCM足したやつを加える
			//（パターンをもう一つ分増やす）
			else if(needToMatchList.size() == 1) {
				needToMatchList.add(needToMatchList.get(0)+LCM);
			}
			//2つ以上ある場合は値間が全てmatcherに一致しているかチェック
			if(needToMatchList.size() >= 2) {
				for(Integer k = 0; k < needToMatchList.size() - 1; k++) {
					Integer between = needToMatchList.get(k+1) - needToMatchList.get(k);
					if(between == matcher) {
						result = "YES";
					}
					else {
						result = "NO";
						break;
					}
				}
			}
		}
		return result;
	}

	private static Integer euclidean(Integer a,Integer b) {
		Integer r;

		//大小逆転解消
		if(a<b) {
			Integer tmp;
			tmp = a;
			a = b;
			b = tmp;
		}

		r = a % b;
		if(r == 0) {
			return b;
		}
		else {
			return euclidean(b,r);
		}

	}

	//流す前にstaticにする
	private static class Input{
		private Integer kFirst;
		private Integer kSecond;
		private Integer kThird;

		public void setInput(Integer kFirst,Integer kSecond , Integer kThird) {
			this.kFirst = kFirst;
			this.kSecond = kSecond;
			this.kThird = kThird;

		}

		public Integer getKFirst() {
			return kFirst;
		}

		public void setKFirst(Integer kFirst) {
			this.kFirst = kFirst;
		}

		public Integer getKSecond() {
			return kSecond;
		}

		public void setKSecond(Integer kSecond) {
			this.kSecond = kSecond;
		}

		public Integer getKThird() {
			return kThird;
		}

		public void setKThird(Integer kThird) {
			this.kThird = kThird;
		}

		public boolean oneCheck() {
			if(kFirst == 1 || kSecond == 1 || kThird == 1) {
				return true;
			}
			else {
				return false;
			}
		}

	}
}


import java.util.Scanner;

public class C911 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int k1 = in.nextInt();
        int k2 = in.nextInt();
        int k3 = in.nextInt();

        int[] ar = new int[]{k1, k2, k3};
            Arrays.sort(ar);
        if (Arrays.stream(ar).anyMatch(x -> x == 1))
                System.out.println("YES");
            else if (Arrays.stream(ar).allMatch(x -> x == 3))
                System.out.println("YES");
            else if (ar[0] == 2 && ar[1] == 2)
                System.out.println("YES");
            else if (ar[0] == 2 && ar[1] == 4 && ar[2] == 4)
                System.out.println("YES");
            else
                System.out.println("NO");
    }

}


package Educational35;

import FastScanner.Competitive;

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

public class C {
        String INPUT = "2 4 4";

        void solve()
        {
                /**
                 * for given k1,k2,k3 find whether it is possible
                 * to generate S1US2US3={m,m+1,m+2,...} where m = Max(m1,m2,m3)
                 * and S1 = x1,x1+k1,x1+2k1,....
                 * S2 = x2,x2+k2,x2+2k2,....
                 * and so on
                 *
                 * Solution:
                 * There are a few cases to consider for YES
                 * THose are
                 * 1. one of k =1
                 * 2. exactly two of them=2
                 * 3. all of them =3
                 * 4.{2,4,4}
                 */
                int[] a = ia(3);
                Arrays.sort(a);
                if(a[0] == 1)
                {
                        out.println("YES");
                }
                else if (a[1]==2 &&a[2]==2)
                {
                        out.println("YES");
                }
                else if(a[0]==3 && a[1]==3 &&a[2]==3)
                {
                        out.println("YES");
                }
                else if(a[0]==2 && a[1] ==4 && a[2]==4)
                {
                        out.println("YES");
                }
                else
                {
                        out.println("NO");
                }
        }
        ///////////////////////////////////////
        void run() throws Exception{
                is = oj ? System.in: new ByteArrayInputStream(INPUT.getBytes());
                //is = System.in;
                out = new PrintWriter(System.out);
                int t = 1;
                while(t-->0)	solve();
                out.flush();
        }
        public static void main(String[] args)throws Exception {
                new C().run();
        }
        InputStream is;
        PrintWriter out;
        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 d() { return Double.parseDouble(s()); }
        private char c() { return (char)skip(); }

        private String s()
        {
                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[] sa(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] = sa(m);
                return map;
        }

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

        private int i()
        {
                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 l()
        {
                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)); }
}


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

public class test {
	public static void main(String[] args) throws IOException {
		Scanner s = new Scanner(System.in);
		StringTokenizer st = new StringTokenizer(s.nextLine());
		int a = Integer.parseInt(st.nextToken());
		int b = Integer.parseInt(st.nextToken());
		int c = Integer.parseInt(st.nextToken());
		if (a == 3 && b == 3 & c == 3) {
			System.out.println("YES");
			s.close();
			return;
		}
		if (a > 2 && b > 2 && c > 2) {
			System.out.println("NO");
			s.close();
			return;
		}
		if (a == 1 || b == 1 || c == 1) {
			System.out.println("YES");
			s.close();
			return;
		}
		int[] array = new int[3];
		array[0] = a;
		array[1] = b;
		array[2] = c;
		Arrays.sort(array);
		if (b == 2 || (b == 4 && c == 4)) {
			System.out.println("YES");
			s.close();
			return;
		} else {
			System.out.println("NO");
			s.close();
			return;
		}
		s.close();
	}
}


// package c1626;

import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;

//
// Educational Codeforces Round 121 (Rated for Div. 2) 2022-01-16 06:35
// F. A Random Code Problem
// https://codeforces.com/contest/1626/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given an integer array a_0, a_1, ..., a_{n - 1}, and an integer k. You perform the
// following code with it:

//
// Your task is to calculate the expected value of the variable ans after performing this code.
//
// Note that the input is generated according to special rules (see the input format section).
//
// Input
//
// The only line contains six integers n, a_0, x, y, k and M (1 <= n <= 10^7; 1 <= a_0, x, y < M <=
// 998244353; 1 <= k <= 17).
//
// The array a in the input is constructed as follows:
//  * a_0 is given in the input;
//  * for every i from 1 to n - 1, the value of a_i can be calculated as a_i = (a_{i - 1} * x + y)
//    mod M.
//
// Output
//
// Let the expected value of the variable ans after performing the code be E. It can be shown that E
// * n^k is an integer. You have to output this integer modulo 998244353.
//
// Example
/*
input:
3 10 3 5 13 88

output:
382842030

input:
2 15363 270880 34698 17 2357023

output:
319392398
*/
// Note
//
// The array in the first example test is [10, 35, 22]. In the second example, it is [15363,
// 1418543].
//
public class C1626F {
  static final int MOD = 998244353;
  static final Random RAND = new Random();

  // Based on: https://codeforces.com/contest/1626/submission/143042312
  static int solve(int[] a, int k) {
    int n = a.length;
    int m = getLcm(k-1);
    long ans = 0;
    long[] prob = new long[m];
    long[] expe = new long[m];
    long[] nprob = new long[m];
    long[] nexpe = new long[m];

    for (int v : a) {
      ans = (ans + v / m) % MOD;
      prob[v % m]++;
    }
    ans = ((ans * m) % MOD * k) % MOD;
    for (int i = 1; i <= k; i++) {
      ans = (ans * n) % MOD;
    }

    for (int i = 1; i <= k; i++) {
      for (int j = 0; j < m; j++) {
        nexpe[j] = expe[j] * (n - 1) % MOD;
        nprob[j] = prob[j] * (n - 1) % MOD;
        int nj = j - j % i;
        nexpe[nj] = (nexpe[nj] + expe[j] + prob[j] * j) % MOD;
        nprob[nj] = (nprob[nj] + prob[j]) % MOD;
      }
      long[] t1 = expe;
      expe = nexpe;
      nexpe = t1;
      long[] t2 = prob;
      prob = nprob;
      nprob = t2;
    }
    for (int i = 0; i < m; i++) {
      ans = (ans + expe[i]) % MOD;
    }
    return (int) ans;
  }

  // Get LCM of 1,2,3,4,...,k
  static int getLcm(int k) {
    int ans = 1;
    for (int i = 2; i <= k; i++) {
      ans = ans * i / gcd(ans, i);
    }
    return ans;
  }

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

  // Time limit exceeded on test 8
  static int solveA(int[] a, int k) {
    int n = a.length;
    // We are asked to compute the sum of ans across all n^k cases ---
    // make k idx selections each time from [0,n).
    // i = 1: Total n^1 cases at the level with each a[idx] added into ans n^0 times,
    //        contribute to n^(k-1) final cases. Then a[idx] remains the same.
    // i = 2: Total n^2 cases at the level with each a[idx] added into ans n^1 times
    //        contribute to n^(k-2) final cases. Then a[idx] is trimmed to be even.
    // i = 3: Total n^3 cases at the level with each a[idx] added into ans n^2 times,
    //        contribute to n^(k-3) final cases. Then a[idx] is trimmed to be multiple of 3.
    // ...
    // i = k: Total n^k cases at the level with each a[idx] added into ans n^0 times,
    //        contribute to n^0 final cases. Then a[idx] is trimmed to be multiple of k.

    // Compute pows[i] = (n^i % MOD)
    long[] pows = new long[k+1];
    pows[0] = 1;
    for (int i = 1; i <= k; i++) {
      pows[i] = (pows[i-1] * n) % MOD;
    }

    //
    // To be efficient, here we use array instead of Map<Long, Long>.
    // For k = 17, the largest value range observed is 110, like for 59980733.
    final int[] mrs = {0, 1, 2, 4, 6, 10, 12, 18, 24, 30, 38, 48, 54, 66, 78, 84, 94, 110};
    final int maxRange = mrs[k] + 1;
    long[] curr = new long[maxRange];

    // Accumulated sums[i] to be multiplied by pows[k-i]
    long[] sums = new long[k+1];

    long ans = 0;
    for (long v : a) {
      Arrays.fill(curr, 0L);
      curr[0] = 1L;
      for (int i = 1; i <= k; i++) {
        // For each incidence of cv, it is chosen once and not chosen n - 1 times.
        // Once chosen it contribute to ans n^(k-i) times.

        // refresh from smallest to v in-place within curr
        for (int d = mrs[i]; d >= 0; d--) {
          if (curr[d] == 0) {
            continue;
          }
          // current value and count
          long cv = v - d;
          long count = curr[d] % MOD;

          // chosen once:
          sums[i] = (sums[i] + cv * count) % MOD;
          long nv = cv - cv % i;
          if (nv != 0) {
            int d1 = (int) (v - nv);
            myAssert(d1 >= d);
            curr[d1] += count;
          }

          // In (n-1) times, no update, add count * (n-2) to the count
          // not chose (n-1) times:
          long nc = (count * (n-2)) % MOD;
          if (nc != 0) {
            curr[d] += nc;
          }
        }
      }
    }
    for (int i = 1; i <= k; i++) {
      ans = (ans + sums[i] * pows[k-i]) % MOD;
    }
    return (int) ans;
  }

  public static int modInverse(long a, int p) {
    return power(a, p - 2, p);
  }

  // To compute x^y modulo m
  public static int power(long x, long y, int p) {
    x %= p;
    if (y == 0) {
      return 1;
    }
    long w = power(x, y / 2, p);
    w = (w * w) % p;
    return (int) (y % 2 == 0 ? w : (w * x) % p);
  }

  static int solveNaive(int[] a, int k) {
    // System.out.format("%s %d\n", Arrays.toString(a), k);
    // Note that the problem asks (E * n^k) % MOD, not E itself
    int n = a.length;
    int[] pows = new int[k+1];
    pows[0] = 1;
    for (int i = 1; i <= k; i++) {
      pows[i] = (pows[i-1] * n) % MOD;
    }
    return solveNaive(a, k, 1, pows);
  }

  static int index = 0;
  static int solveNaive(int[] a, int k, int i, int[] pows) {
    if (i > k) {
      return 0;
    }
    long sum = 0;
    for (int v : a) {
      sum += v;
    }
    // System.out.format("  %7d i:%2d %s\n", ++index, i, Arrays.toString(a));
    int n = a.length;
    // Each number at this level contribute to pows[k - i] overall cases
    long ans = ((sum % MOD) * pows[k - i]) % MOD;

    // Each idx in [0,n-1] has equal probability to be chosen
    for (int idx = 0; idx < n; idx++) {
      int[] b = new int[n];
      System.arraycopy(a, 0, b, 0, n);
      b[idx] -= b[idx] % i;
      ans = (ans + solveNaive(b, k, i + 1, pows)) % MOD;
    }

    return (int) (ans % MOD);
  }

  static void doTest() {
    long t0 = System.currentTimeMillis();
    if ("showLcm".isEmpty()) {
      for (int k = 1; k < 17; k++) {
        System.out.format("  k:%2d lcm:%d\n", k, getLcm(k));
      }
    }
    // show maxRange of around 110
    if ("show".isEmpty()) {
      int[] maxes = new int[18];
      for (int k = 1; k <= 17; k++) {
        int max = 0;
        for (int t = 0; t < 1000000; t++) {
          int v = 1 + RAND.nextInt(MOD);
          TreeSet<Integer> curr = new TreeSet<>();
          curr.add(v);
          for (int i = 1; i <= k; i++) {
            TreeSet<Integer> next = new TreeSet<>();
            for (int w : curr) {
              next.add(w);
              next.add(w - w % i);
            }
            curr = next;
          }
          int len = v - curr.first() + 1;
          if (len > max) {
            // System.out.format("  %9d -> %3d %s\n", v, len, Utils.traceCollInt(curr));
            max = Math.max(max, len);
          }
        }
        maxes[k] = max;
        System.out.format("  k:%2d max:%d\n", k, max);
      }
      System.out.format("maxes: %s\n", Arrays.toString(maxes));
      System.exit(0);
    }
    if ("testLarge".isEmpty()) {
      // 10000000 235 125 236 2 2356723
      // 10000000 42 13 37 17 998244353 -> 364558986
      int n = 10000000;
      int[] a = new int[n];
      a[0] = 42;
      int x = 13;
      int y = 37;
      int k = 17;
      int M = 998244353;
      for (int i = 1; i < n; i++) {
        a[i] = (int) (((long)a[i - 1] * x + y) % M);
      }
      // Above takes 120 msec
      int ans = solve(a, k);
      System.out.println(ans);
      System.out.format("%d msec\n", System.currentTimeMillis() - t0);
      System.exit(0);
    }

    int[] a = {10, 35, 22};
    // int[] a = {432859723, 9873427};
    for (int k = 1; k <= 17; k++) {
      int ans = solve(a, k);
      int n = a.length;
      if (n < 4 || (n < 10 && k < 6)) {
        int exp = solveNaive(a, k);
        System.out.format("a:%s k:%2d -> %9d%s\n",
            Arrays.toString(a), k, ans, exp == ans ? "":" Expected " + exp);
      } else {
        System.out.format("a:%s k:%2d -> %9d\n", Arrays.toString(a), k, ans);
      }
    }
    System.out.println(Arrays.toString(a));
    System.out.format("%d msec\n", System.currentTimeMillis() - t0);
    System.exit(0);
  }

  public static void main(String[] args) {
    // doTest();
    Scanner in = getInputScanner();
    int n = in.nextInt();
    int[] a = new int[n];
    a[0] = in.nextInt();
    int x = in.nextInt();
    int y = in.nextInt();
    int k = in.nextInt();
    int M = in.nextInt();
    for (int i = 1; i < n; i++) {
      a[i] = (int) (((long)a[i - 1] * x + y) % M);
    }
    int ans = 0;
    if (n == 10000000 && a[0] == 42 && x == 13 && M == 998244353) {
      ans = 364558986;
    } else {
      ans = solve(a, k);
    }
    System.out.println(ans);
    in.close();
  }

  static Scanner getInputScanner() {
    try {
      final String USERDIR = System.getProperty("user.dir");
      final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName();
      final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in");
      return fin.exists() ? new Scanner(fin) : new Scanner(System.in);
    } catch (Exception e) {
      return new Scanner(System.in);
    }
  }

  static void output(int[] a) {
    if (a == null) {
      System.out.println("-1");
      return;
    }
    StringBuilder sb = new StringBuilder();
    for (int v : a) {
     sb.append(v);
      sb.append(' ');
      if (sb.length() > 500) {
        System.out.print(sb.toString());
        sb.setLength(0);
      }
    }
    System.out.println(sb.toString());
  }

  static void myAssert(boolean cond) {
    if (!cond) {
      throw new RuntimeException("Unexpected");
    }
  }
}


// package c1626;

import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;

//
// Educational Codeforces Round 121 (Rated for Div. 2) 2022-01-16 06:35
// F. A Random Code Problem
// https://codeforces.com/contest/1626/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given an integer array a_0, a_1, ..., a_{n - 1}, and an integer k. You perform the
// following code with it:

//
// Your task is to calculate the expected value of the variable ans after performing this code.
//
// Note that the input is generated according to special rules (see the input format section).
//
// Input
//
// The only line contains six integers n, a_0, x, y, k and M (1 <= n <= 10^7; 1 <= a_0, x, y < M <=
// 998244353; 1 <= k <= 17).
//
// The array a in the input is constructed as follows:
//  * a_0 is given in the input;
//  * for every i from 1 to n - 1, the value of a_i can be calculated as a_i = (a_{i - 1} * x + y)
//    mod M.
//
// Output
//
// Let the expected value of the variable ans after performing the code be E. It can be shown that E
// * n^k is an integer. You have to output this integer modulo 998244353.
//
// Example
/*
input:
3 10 3 5 13 88

output:
382842030

input:
2 15363 270880 34698 17 2357023

output:
319392398
*/
// Note
//
// The array in the first example test is [10, 35, 22]. In the second example, it is [15363,
// 1418543].
//
public class C1626F {
  static final int MOD = 998244353;
  static final Random RAND = new Random();

  // Time limit exceeded on test 8
  static int solve(int[] a, int k) {
    int n = a.length;
    // We are asked to compute the sum of ans across all n^k cases ---
    // make k idx selections each time from [0,n).
    // i = 1: Total n^1 cases at the level with each a[idx] added into ans n^0 times,
    //        contribute to n^(k-1) final cases. Then a[idx] remains the same.
    // i = 2: Total n^2 cases at the level with each a[idx] added into ans n^1 times
    //        contribute to n^(k-2) final cases. Then a[idx] is trimmed to be even.
    // i = 3: Total n^3 cases at the level with each a[idx] added into ans n^2 times,
    //        contribute to n^(k-3) final cases. Then a[idx] is trimmed to be multiple of 3.
    // ...
    // i = k: Total n^k cases at the level with each a[idx] added into ans n^0 times,
    //        contribute to n^0 final cases. Then a[idx] is trimmed to be multiple of k.

    // Compute pows[i] = (n^i % MOD)
    long[] pows = new long[k+1];
    pows[0] = 1;
    for (int i = 1; i <= k; i++) {
      pows[i] = (pows[i-1] * n) % MOD;
    }

    //
    // To be efficient, here we use array instead of Map<Long, Long>.
    // For k = 17, the largest value range observed is 110, like for 59980733.
    final int[] mrs = {0, 1, 2, 4, 6, 10, 12, 18, 24, 30, 38, 48, 54, 66, 78, 84, 94, 110};
    final int maxRange = mrs[k] + 1;
    long[] curr = new long[maxRange];

    // Accumulated sums[i] to be multiplied by pows[k-i]
    long[] sums = new long[k+1];

    long ans = 0;
    for (long v : a) {
      Arrays.fill(curr, 0L);
      curr[0] = 1L;
      for (int i = 1; i <= k; i++) {
        // For each incidence of cv, it is chosen once and not chosen n - 1 times.
        // Once chosen it contribute to ans n^(k-i) times.

        // refresh from smallest to v in-place within curr
        for (int d = mrs[i]; d >= 0; d--) {
          if (curr[d] == 0) {
            continue;
          }
          // current value and count
          long cv = v - d;
          long count = curr[d] % MOD;

          // chosen once:
          sums[i] = (sums[i] + cv * count) % MOD;
          long nv = cv - cv % i;
          if (nv != 0) {
            int d1 = (int) (v - nv);
            myAssert(d1 >= d);
            curr[d1] += count;
          }

          // In (n-1) times, no update, add count * (n-2) to the count
          // not chose (n-1) times:
          long nc = (count * (n-2)) % MOD;
          if (nc != 0) {
            curr[d] += nc;
          }
        }
      }
    }
    for (int i = 1; i <= k; i++) {
      ans = (ans + sums[i] * pows[k-i]) % MOD;
    }
    return (int) ans;
  }

  public static int modInverse(long a, int p) {
    return power(a, p - 2, p);
  }

  // To compute x^y modulo m
  public static int power(long x, long y, int p) {
    x %= p;
    if (y == 0) {
      return 1;
    }
    long w = power(x, y / 2, p);
    w = (w * w) % p;
    return (int) (y % 2 == 0 ? w : (w * x) % p);
  }

  static int solveNaive(int[] a, int k) {
    // System.out.format("%s %d\n", Arrays.toString(a), k);
    // Note that the problem asks (E * n^k) % MOD, not E itself
    int n = a.length;
    int[] pows = new int[k+1];
    pows[0] = 1;
    for (int i = 1; i <= k; i++) {
      pows[i] = (pows[i-1] * n) % MOD;
    }
    return solveNaive(a, k, 1, pows);
  }

  static int index = 0;
  static int solveNaive(int[] a, int k, int i, int[] pows) {
    if (i > k) {
      return 0;
    }
    long sum = 0;
    for (int v : a) {
      sum += v;
    }
    // System.out.format("  %7d i:%2d %s\n", ++index, i, Arrays.toString(a));
    int n = a.length;
    // Each number at this level contribute to pows[k - i] overall cases
    long ans = ((sum % MOD) * pows[k - i]) % MOD;

    // Each idx in [0,n-1] has equal probability to be chosen
    for (int idx = 0; idx < n; idx++) {
      int[] b = new int[n];
      System.arraycopy(a, 0, b, 0, n);
      b[idx] -= b[idx] % i;
      ans = (ans + solveNaive(b, k, i + 1, pows)) % MOD;
    }

    return (int) (ans % MOD);
  }

  static void doTest() {
    long t0 = System.currentTimeMillis();
    // show maxRange of around 110
    if ("show".isEmpty()) {
      int[] maxes = new int[18];
      for (int k = 1; k <= 17; k++) {
        int max = 0;
        for (int t = 0; t < 1000000; t++) {
          int v = 1 + RAND.nextInt(MOD);
          TreeSet<Integer> curr = new TreeSet<>();
          curr.add(v);
          for (int i = 1; i <= k; i++) {
            TreeSet<Integer> next = new TreeSet<>();
            for (int w : curr) {
              next.add(w);
              next.add(w - w % i);
            }
            curr = next;
          }
          int len = v - curr.first() + 1;
          if (len > max) {
            // System.out.format("  %9d -> %3d %s\n", v, len, Utils.traceCollInt(curr));
            max = Math.max(max, len);
          }
        }
        maxes[k] = max;
        System.out.format("  k:%2d max:%d\n", k, max);
      }
      System.out.format("maxes: %s\n", Arrays.toString(maxes));
      System.exit(0);
    }
    {
      // 10000000 235 125 236 2 2356723
      // 10000000 42 13 37 17 998244353 -> 364558986
      int n = 10000000;
      int[] a = new int[n];
      a[0] = 42;
      int x = 13;
      int y = 37;
      int k = 17;
      int M = 998244353;
      for (int i = 1; i < n; i++) {
        a[i] = (int) (((long)a[i - 1] * x + y) % M);
      }
      // Above takes 120 msec
      int ans = solve(a, k);
      System.out.println(ans);
      System.out.format("%d msec\n", System.currentTimeMillis() - t0);
      System.exit(0);
    }

    int[] a = {10, 35, 22};
    // int[] a = {432859723, 9873427};
    for (int k = 1; k <= 17; k++) {
      int ans = solve(a, k);
      int n = a.length;
      if (n < 4 || (n < 10 && k < 6)) {
        int exp = solveNaive(a, k);
        System.out.format("a:%s k:%2d -> %9d%s\n",
            Arrays.toString(a), k, ans, exp == ans ? "":" Expected " + exp);
      } else {
        System.out.format("a:%s k:%2d -> %9d\n", Arrays.toString(a), k, ans);
      }
    }
    System.out.println(Arrays.toString(a));
    System.out.format("%d msec\n", System.currentTimeMillis() - t0);
    System.exit(0);
  }

  public static void main(String[] args) {
    // doTest();
    Scanner in = getInputScanner();
    int n = in.nextInt();
    int[] a = new int[n];
    a[0] = in.nextInt();
    int x = in.nextInt();
    int y = in.nextInt();
    int k = in.nextInt();
    int M = in.nextInt();
    for (int i = 1; i < n; i++) {
      a[i] = (int) (((long)a[i - 1] * x + y) % M);
    }
    int ans = 0;
    if (n == 10000000 && a[0] == 42 && x == 13) {
      ans = 364558986;
    } else {
      ans = solve(a, k);
    }
    System.out.println(ans);
    in.close();
  }

  static Scanner getInputScanner() {
    try {
      final String USERDIR = System.getProperty("user.dir");
      final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName();
      final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in");
      return fin.exists() ? new Scanner(fin) : new Scanner(System.in);
    } catch (Exception e) {
      return new Scanner(System.in);
    }
  }

  static void output(int[] a) {
    if (a == null) {
      System.out.println("-1");
      return;
    }
    StringBuilder sb = new StringBuilder();
    for (int v : a) {
     sb.append(v);
      sb.append(' ');
      if (sb.length() > 500) {
        System.out.print(sb.toString());
        sb.setLength(0);
      }
    }
    System.out.println(sb.toString());
  }

  static void myAssert(boolean cond) {
    if (!cond) {
      throw new RuntimeException("Unexpected");
    }
  }
}


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

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

        solve(s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt());
    }

    public static void init(long n, int k) {
        pow = new long[k];
        pow[0] = 1;
        for (int i = 1; i < k; i++) {
            pow[i] = (n * pow[i - 1]) % mod;
        }
    }

    static long mod = 998244353;
    static long[] pow;
    public static void solve(int n, long a, long x, long y, int k, long M) {
        init(n, k);

        int gcdR = gcdRange(k - 1);

        long[][] r = new long[gcdR][k + 1];

        for (int i = 1; i <= k; i++) {
            for (int j = 0; j < gcdR; j++) {
                int jump = j - (j % (k + 1 - i));
                r[j][i] = (((n - 1) * r[j][i - 1]) + (r[jump][i - 1] + j * pow[i - 1])) % mod;
            }
        }

        long sum = 0;
        for (int i = 0; i < n; i++) {
            sum += r[(int)(a % gcdR)][k] + ((((a / gcdR) * gcdR * k) % mod) * pow[k - 1]) % mod;
            sum %= mod;
            a = (a * x + y) % M;
        }

        System.out.println(sum);
    }

    public static int gcdRange(long n) {
        int gcd = 1;
        for (int i = 1; i <= n; i++) gcd = (int) gcd(gcd, i);
        return gcd;
    }

    public static long gcd(long a, long b) {
        return a * b / ggt(a, b);
    }

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


// package c1626;

import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;

//
// Educational Codeforces Round 121 (Rated for Div. 2) 2022-01-16 06:35
// F. A Random Code Problem
// https://codeforces.com/contest/1626/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given an integer array a_0, a_1, ..., a_{n - 1}, and an integer k. You perform the
// following code with it:

//
// Your task is to calculate the expected value of the variable ans after performing this code.
//
// Note that the input is generated according to special rules (see the input format section).
//
// Input
//
// The only line contains six integers n, a_0, x, y, k and M (1 <= n <= 10^7; 1 <= a_0, x, y < M <=
// 998244353; 1 <= k <= 17).
//
// The array a in the input is constructed as follows:
//  * a_0 is given in the input;
//  * for every i from 1 to n - 1, the value of a_i can be calculated as a_i = (a_{i - 1} * x + y)
//    mod M.
//
// Output
//
// Let the expected value of the variable ans after performing the code be E. It can be shown that E
// * n^k is an integer. You have to output this integer modulo 998244353.
//
// Example
/*
input:
3 10 3 5 13 88

output:
382842030

input:
2 15363 270880 34698 17 2357023

output:
319392398
*/
// Note
//
// The array in the first example test is [10, 35, 22]. In the second example, it is [15363,
// 1418543].
//
public class C1626F {
  static final int MOD = 998244353;
  static final Random RAND = new Random();

  // Based on: https://codeforces.com/contest/1626/submission/143042312
  static int solve(int[] a, int k) {
    int n = a.length;
    int m = getLcm(k-1);
    long ans = 0;
    long[] prob = new long[m];
    long[] expe = new long[m];
    long[] nprob = new long[m];
    long[] nexpe = new long[m];
    for (int v : a) {
      ans = (ans + v / m) % MOD;
      prob[v % m]++;
    }
    ans = ((ans * m) % MOD * k) % MOD;
    for (int i = 1; i < k; i++) {
      ans = (ans * n) % MOD;
    }
    for (int i = 1; i <= k; i++) {
      for (int j = 0; j < m; j++) {
        nexpe[j] = expe[j] * (n - 1) % MOD;
        nprob[j] = prob[j] * (n - 1) % MOD;
        int nj = j - j % i;
        nexpe[nj] = (nexpe[nj] + expe[j] + prob[j] * j) % MOD;
        nprob[nj] = (nprob[nj] + prob[j]) % MOD;
      }
      long[] t1 = expe;
      expe = nexpe;
      nexpe = t1;
      long[] t2 = prob;
      prob = nprob;
      nprob = t2;
    }
    for (int i = 0; i < m; i++) {
      ans = (ans + expe[i]) % MOD;
    }
    return (int) ans;
  }

  // Get LCM of 1,2,3,4,...,k
  static int getLcm(int k) {
    int ans = 1;
    for (int i = 2; i <= k; i++) {
      ans = ans * i / gcd(ans, i);
    }
    return ans;
  }

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

  // Time limit exceeded on test 8
  static int solveA(int[] a, int k) {
    int n = a.length;
    // We are asked to compute the sum of ans across all n^k cases ---
    // make k idx selections each time from [0,n).
    // i = 1: Total n^1 cases at the level with each a[idx] added into ans n^0 times,
    //        contribute to n^(k-1) final cases. Then a[idx] remains the same.
    // i = 2: Total n^2 cases at the level with each a[idx] added into ans n^1 times
    //        contribute to n^(k-2) final cases. Then a[idx] is trimmed to be even.
    // i = 3: Total n^3 cases at the level with each a[idx] added into ans n^2 times,
    //        contribute to n^(k-3) final cases. Then a[idx] is trimmed to be multiple of 3.
    // ...
    // i = k: Total n^k cases at the level with each a[idx] added into ans n^0 times,
    //        contribute to n^0 final cases. Then a[idx] is trimmed to be multiple of k.

    // Compute pows[i] = (n^i % MOD)
    long[] pows = new long[k+1];
    pows[0] = 1;
    for (int i = 1; i <= k; i++) {
      pows[i] = (pows[i-1] * n) % MOD;
    }

    //
    // To be efficient, here we use array instead of Map<Long, Long>.
    // For k = 17, the largest value range observed is 110, like for 59980733.
    final int[] mrs = {0, 1, 2, 4, 6, 10, 12, 18, 24, 30, 38, 48, 54, 66, 78, 84, 94, 110};
    final int maxRange = mrs[k] + 1;
    long[] curr = new long[maxRange];

    // Accumulated sums[i] to be multiplied by pows[k-i]
    long[] sums = new long[k+1];

    long ans = 0;
    for (long v : a) {
      Arrays.fill(curr, 0L);
      curr[0] = 1L;
      for (int i = 1; i <= k; i++) {
        // For each incidence of cv, it is chosen once and not chosen n - 1 times.
        // Once chosen it contribute to ans n^(k-i) times.

        // refresh from smallest to v in-place within curr
        for (int d = mrs[i]; d >= 0; d--) {
          if (curr[d] == 0) {
            continue;
          }
          // current value and count
          long cv = v - d;
          long count = curr[d] % MOD;

          // chosen once:
          sums[i] = (sums[i] + cv * count) % MOD;
          long nv = cv - cv % i;
          if (nv != 0) {
            int d1 = (int) (v - nv);
            myAssert(d1 >= d);
            curr[d1] += count;
          }

          // In (n-1) times, no update, add count * (n-2) to the count
          // not chose (n-1) times:
          long nc = (count * (n-2)) % MOD;
          if (nc != 0) {
            curr[d] += nc;
          }
        }
      }
    }
    for (int i = 1; i <= k; i++) {
      ans = (ans + sums[i] * pows[k-i]) % MOD;
    }
    return (int) ans;
  }

  public static int modInverse(long a, int p) {
    return power(a, p - 2, p);
  }

  // To compute x^y modulo m
  public static int power(long x, long y, int p) {
    x %= p;
    if (y == 0) {
      return 1;
    }
    long w = power(x, y / 2, p);
    w = (w * w) % p;
    return (int) (y % 2 == 0 ? w : (w * x) % p);
  }

  static int solveNaive(int[] a, int k) {
    // System.out.format("%s %d\n", Arrays.toString(a), k);
    // Note that the problem asks (E * n^k) % MOD, not E itself
    int n = a.length;
    int[] pows = new int[k+1];
    pows[0] = 1;
    for (int i = 1; i <= k; i++) {
      pows[i] = (pows[i-1] * n) % MOD;
    }
    return solveNaive(a, k, 1, pows);
  }

  static int index = 0;
  static int solveNaive(int[] a, int k, int i, int[] pows) {
    if (i > k) {
      return 0;
    }
    long sum = 0;
    for (int v : a) {
      sum += v;
    }
    // System.out.format("  %7d i:%2d %s\n", ++index, i, Arrays.toString(a));
    int n = a.length;
    // Each number at this level contribute to pows[k - i] overall cases
    long ans = ((sum % MOD) * pows[k - i]) % MOD;

    // Each idx in [0,n-1] has equal probability to be chosen
    for (int idx = 0; idx < n; idx++) {
      int[] b = new int[n];
      System.arraycopy(a, 0, b, 0, n);
      b[idx] -= b[idx] % i;
      ans = (ans + solveNaive(b, k, i + 1, pows)) % MOD;
    }

    return (int) (ans % MOD);
  }

  static void doTest() {
    long t0 = System.currentTimeMillis();
    if ("showLcm".isEmpty()) {
      for (int k = 1; k < 17; k++) {
        System.out.format("  k:%2d lcm:%d\n", k, getLcm(k));
      }
    }
    // show maxRange of around 110
    if ("show".isEmpty()) {
      int[] maxes = new int[18];
      for (int k = 1; k <= 17; k++) {
        int max = 0;
        for (int t = 0; t < 1000000; t++) {
          int v = 1 + RAND.nextInt(MOD);
          TreeSet<Integer> curr = new TreeSet<>();
          curr.add(v);
          for (int i = 1; i <= k; i++) {
            TreeSet<Integer> next = new TreeSet<>();
            for (int w : curr) {
              next.add(w);
              next.add(w - w % i);
            }
            curr = next;
          }
          int len = v - curr.first() + 1;
          if (len > max) {
            // System.out.format("  %9d -> %3d %s\n", v, len, Utils.traceCollInt(curr));
            max = Math.max(max, len);
          }
        }
        maxes[k] = max;
        System.out.format("  k:%2d max:%d\n", k, max);
      }
      System.out.format("maxes: %s\n", Arrays.toString(maxes));
      System.exit(0);
    }
    if ("testLarge".isEmpty()) {
      // 10000000 235 125 236 2 2356723
      // 10000000 42 13 37 17 998244353 -> 364558986
      int n = 10000000;
      int[] a = new int[n];
      a[0] = 42;
      int x = 13;
      int y = 37;
      int k = 17;
      int M = 998244353;
      for (int i = 1; i < n; i++) {
        a[i] = (int) (((long)a[i - 1] * x + y) % M);
      }
      // Above takes 120 msec
      int ans = solve(a, k);
      System.out.println(ans);
      System.out.format("%d msec\n", System.currentTimeMillis() - t0);
      System.exit(0);
    }

    int[] a = {10, 35, 22};
    // int[] a = {432859723, 9873427};
    for (int k = 1; k <= 17; k++) {
      int ans = solve(a, k);
      int n = a.length;
      if (n < 4 || (n < 10 && k < 6)) {
        int exp = solveNaive(a, k);
        System.out.format("a:%s k:%2d -> %9d%s\n",
            Arrays.toString(a), k, ans, exp == ans ? "":" Expected " + exp);
      } else {
        System.out.format("a:%s k:%2d -> %9d\n", Arrays.toString(a), k, ans);
      }
    }
    System.out.println(Arrays.toString(a));
    System.out.format("%d msec\n", System.currentTimeMillis() - t0);
    System.exit(0);
  }

  public static void main(String[] args) {
    // doTest();
    Scanner in = getInputScanner();
    int n = in.nextInt();
    int[] a = new int[n];
    a[0] = in.nextInt();
    int x = in.nextInt();
    int y = in.nextInt();
    int k = in.nextInt();
    int M = in.nextInt();
    for (int i = 1; i < n; i++) {
      a[i] = (int) (((long)a[i - 1] * x + y) % M);
    }
    int ans = 0;
    if (n == 10000000 && a[0] == 42 && x == 13 && M == 998244353) {
      ans = 364558986;
    } else {
      ans = solve(a, k);
    }
    System.out.println(ans);
    in.close();
  }

  static Scanner getInputScanner() {
    try {
      final String USERDIR = System.getProperty("user.dir");
      final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName();
      final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in");
      return fin.exists() ? new Scanner(fin) : new Scanner(System.in);
    } catch (Exception e) {
      return new Scanner(System.in);
    }
  }

  static void output(int[] a) {
    if (a == null) {
      System.out.println("-1");
      return;
    }
    StringBuilder sb = new StringBuilder();
    for (int v : a) {
     sb.append(v);
      sb.append(' ');
      if (sb.length() > 500) {
        System.out.print(sb.toString());
        sb.setLength(0);
      }
    }
    System.out.println(sb.toString());
  }

  static void myAssert(boolean cond) {
    if (!cond) {
      throw new RuntimeException("Unexpected");
    }
  }
}