using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace Codeforces
{
    class A
    {
        private static ThreadStart s_threadStart = new A().Go;
        private static bool s_time = false;
        private static double s_eps = 1e-16;

        HashSet<long>[] adj;

        private void Go()
        {
            long n = GetInt();
            long m = GetInt();

            adj = new HashSet<long>[n];
            for (int i = 0; i < n; i++)
            {
                adj[i] = new HashSet<long>();
            }

            for (int i = 0; i < m; i++)
            {
                long x = GetInt() - 1;
                long y = GetInt() - 1;
                adj[x].Add(y);
                adj[y].Add(x);
            }

            int[] visited = new int[n];

            for (int i = 0; i < n; i++)
            {
                if (adj[i].Count == n - 1)
                    visited[i] = -1;
            }

            int compCount = 0;

            for (int i = 0; i < n; i++)
            {
                if (visited[i] == 0)
                {
                    Queue<Tuple<long, int>> q = new Queue<Tuple<long, int>>();
                    visited[i] = ++compCount;
                    q.Enqueue(new Tuple<long, int>(i, compCount));
                    while (q.Count > 0)
                    {
                        var node = q.Dequeue();
                        long x = node.Item1;
                        foreach (long child in adj[x])
                        {
                            if (visited[child] == 0)
                            {
                                q.Enqueue(new Tuple<long, int>(child, compCount));
                                visited[child] = compCount;
                            }
                        }
                    }
                }
            }

            if (compCount > 2)
            {
                Wl("No");
                return;
            }

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (i != j && !adj[i].Contains(j) && (visited[i] + visited[j]) != 3)
                    {
                        Wl("No");
                        return;
                    }
                }
            }

            Wl("Yes");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n; i++)
            {
                if (visited[i] == -1) sb.Append('b');
                else if (visited[i] == 1) sb.Append('a');
                else sb.Append('c');
            }
            Wl(sb.ToString());
        }

        #region Template

        public static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            Thread main = new Thread(new ThreadStart(s_threadStart), 200 * 1024 * 1024);
            timer.Start();
            main.Start();
            main.Join();
            timer.Stop();
            if (s_time)
                Wl(timer.ElapsedMilliseconds);
        }

        private static IEnumerator<string> ioEnum;
        private static string GetString()
        {
            while (ioEnum == null || !ioEnum.MoveNext())
            {
                ioEnum = Console.ReadLine().Split().AsEnumerable().GetEnumerator();
            }

            return ioEnum.Current;
        }

        private static int GetInt()
        {
            return int.Parse(GetString(), CultureInfo.InvariantCulture);
        }

        private static long GetLong()
        {
            return long.Parse(GetString(), CultureInfo.InvariantCulture);
        }

        private static double GetDouble()
        {
            return double.Parse(GetString(), CultureInfo.InvariantCulture);
        }

        private static List<int> GetIntArr(int n)
        {
            List<int> ret = new List<int>(n);
            for (int i = 0; i < n; i++)
            {
                ret.Add(GetInt());
            }
            return ret;
        }

        private static void Wl<T>(T o)
        {
            if (o is double)
            {
                Wld((o as double?).Value, "");
            }
            else if (o is float)
            {
                Wld((o as float?).Value, "");
            }
            else
                Console.WriteLine(o.ToString());
        }

        private static void Wl<T>(IEnumerable<T> enumerable)
        {
            Wl(string.Join(" ", enumerable.Select(e => e.ToString()).ToArray()));
        }

        private static void Wld(double d, string format)
        {
            Wl(d.ToString(format, CultureInfo.InvariantCulture));
        }

        #endregion
    }
}


using System;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
using System.Collections;

namespace taskA
{
	class newDecimal {
		private Int64 Z, F, kol;
		public newDecimal(decimal t, Int64 Kol) {
			kol = Kol;
			Z = Decimal.ToInt64 (t);
			Int64 p = 1;
			for (int i = 0; i < kol; i ++)
				p *= 10L;
			F = Decimal.ToInt64 ((t - Z) * p);
		}
		public void print () {
			Console.Write ("{0}.", Z);
			int sz = F.ToString ().Length;
			for (int i = 0; i < kol - sz; i ++)
				Console.Write (0);
			Console.Write (F);
		}
	}

	class MainClass
	{
		public static void Swap<T>(ref T lhs, ref T rhs)
		{
			T temp;
			temp = lhs;
			lhs = rhs;
			rhs = temp;
		}

		public static void Main(string[] args) {
			int[] a = Console.ReadLine ().Split (' ').Select (int.Parse).ToArray ();
			int n = a[0];
			int m = a[1];
			int [,] g = new int[n + 1, n + 1];
			char [] s = new char[n + 1];
			for (int i = 1; i <= m; i ++) {
				a = Console.ReadLine ().Split (' ').Select (int.Parse).ToArray ();
				g [a [0], a [1]] = 1;
				g [a [1], a [0]] = 1;
			}
			for (int i = 1; i <= n; i ++) {
				int sum = 0;
				for (int j = 1; j <= n; j ++)
					sum += g[i,j];
				if (sum == n - 1) s[i] = 'b';
			}
			for (int i = 1; i <= n; i ++)
				if (s [i] != 'b') {
					s [i] = 'a';
					break;
				}

			for (int v = 1; v <= n; v ++) {
				if (s [v] == 'b')
					continue;
				char c = s [v];
				for (int to = v + 1; to <= n; to ++) {
					char newC = s [to];
					if (newC == 'b')
						continue;
					if (g [v, to] == 1) {
						if (newC != c && (newC == 'a' || newC == 'b')) {
							Console.WriteLine ("No");
							return;
						}
						if (newC == c)
							continue;
						s [to] = c;
						continue;
					} else {
						if (newC == c && (newC == 'a' || newC == 'b')) {
							Console.WriteLine ("No");
							return;
						}
						if (newC != c && (newC == 'a' || newC == 'b'))
							continue;
						s [to] = c == 'a' ? 'c' : 'a';
					}
				}
			}

			for (int i = 1; i <= n; i ++)
				for (int j = 1; j <= n; j ++) {
					if (i == j)
						continue;
					char c1 = s [i];
					char c2 = s [j];
					if (c1 > c2)
						Swap<char> (ref c1,ref c2);
					if (g [i, j] == 1) {
						if (c1 == c2 || c1 == c2 - 1)
							continue;
						Console.WriteLine ("No");
						return;
					} else {
						if (c1 == c2 - 2)
							continue;
						Console.WriteLine ("No");
						return;
					}
				}
			char[] ss = new char[n];
			for (int i = 1; i <= n; i ++)
				ss [i - 1] = s [i];
			Console.WriteLine ("Yes");
			Console.WriteLine (ss);

		}
	}
}


using System;
using System.Linq;

namespace Hamburgers
{
    class Hamburgers
    {
        static void Main(string[] args)
        {
            string hamburger;
            long[] kitchenPieces, shopPrices;
            long rubles, count, numB = 0, numS = 0, numC = 0;

            hamburger = Console.ReadLine();
            kitchenPieces = Console.ReadLine().Split().Select(long.Parse).ToArray();
            shopPrices = Console.ReadLine().Split().Select(long.Parse).ToArray();
            rubles = long.Parse(Console.ReadLine());

            for (int i = 0; i < hamburger.Length; i++)
            {
                if (hamburger[i] == 'B')
                    numB++;
                else if (hamburger[i] == 'S')
                    numS++;
                else
                    numC++;
            }

            Console.WriteLine(BinarySearch(0, 1L<<45, numB, numS, numC, kitchenPieces, shopPrices, rubles));
        }

        private static long BinarySearch(long start, long end, long numB, long numS, long numC, long[] kitchenPieces, long[] shopPrices, long rubles)
        {
            long mid = (start + end) / 2;

            if (end - start <= 1)
            {
                if (MaxRublesUsed(end, numB, numS, numC, kitchenPieces, shopPrices, rubles))
                    return end;
                else
                    return start;
            }

            if (MaxRublesUsed(mid, numB, numS, numC, kitchenPieces, shopPrices, rubles))
                return BinarySearch(mid, end, numB, numS, numC, kitchenPieces, shopPrices, rubles);
            else
                return BinarySearch(start, mid, numB, numS, numC, kitchenPieces, shopPrices, rubles);
        }

        private static bool MaxRublesUsed(long num, long numB, long numS, long numC, long[] kitchenPieces, long[] shopPrices, long rubles)
        {
            long b, s, c;

            b = Math.Max(0, (numB * num) - kitchenPieces[0]) * shopPrices[0];
            s = Math.Max(0, (numS * num) - kitchenPieces[1]) * shopPrices[1];
            c = Math.Max(0, (numC * num) - kitchenPieces[2]) * shopPrices[2];

            return rubles >= (b + s + c);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

// (づ°ω°)づﾐ★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    public void Solve()
    {
        var cnt = new int[3];
        foreach (char ch in ReadToken())
            cnt["BSC".IndexOf(ch)]++;
        var a = ReadIntArray();
        var b = ReadIntArray();
        long n = ReadLong();

        long l = 0, r = n + 1000;
        while (l < r)
        {
            long mid = (l + r + 1) / 2;
            long s = 0;
            for (int i = 0; i < 3; i++)
                s += Math.Max(0, cnt[i] * mid - a[i]) * b[i];
            if (s > n)
                r = mid - 1;
            else
                l = mid;
        }

        Write(l);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;

    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("cycle.in");
        //writer = new StreamWriter("cycle.out");
#endif
        try
        {
            //            var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //            thread.Start();
            //            thread.Join();
            new Solver().Solve();
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine(ex);
#else
            Console.WriteLine(ex);
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion

    #region Read / Write

    private static Queue<string> currentLineTokens = new Queue<string>();

    private static string[] ReadAndSplitLine()
    {
        return reader.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public static string ReadToken()
    {
        while (currentLineTokens.Count == 0)
            currentLineTokens = new Queue<string>(ReadAndSplitLine());
        return currentLineTokens.Dequeue();
    }

    public static int ReadInt()
    {
        return int.Parse(ReadToken());
    }

    public static long ReadLong()
    {
        return long.Parse(ReadToken());
    }

    public static double ReadDouble()
    {
        return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
    }

    public static int[] ReadIntArray()
    {
        return ReadAndSplitLine().Select(int.Parse).ToArray();
    }

    public static long[] ReadLongArray()
    {
        return ReadAndSplitLine().Select(long.Parse).ToArray();
    }

    public static double[] ReadDoubleArray()
    {
        return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
    }

    public static int[][] ReadIntMatrix(int numberOfRows)
    {
        int[][] matrix = new int[numberOfRows][];
        for (int i = 0; i < numberOfRows; i++)
            matrix[i] = ReadIntArray();
        return matrix;
    }

    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows);
        int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++)
        {
            ret[i] = new int[numberOfRows];
            for (int j = 0; j < numberOfRows; j++)
                ret[i][j] = matrix[j][i];
        }
        return ret;
    }

    public static string[] ReadLines(int quantity)
    {
        string[] lines = new string[quantity];
        for (int i = 0; i < quantity; i++)
            lines[i] = reader.ReadLine().Trim();
        return lines;
    }

    public static void WriteArray<T>(IEnumerable<T> array)
    {
        writer.WriteLine(string.Join(" ", array));
    }

    public static void Write(params object[] array)
    {
        WriteArray(array);
    }

    public static void WriteLines<T>(IEnumerable<T> array)
    {
        foreach (var a in array)
            writer.WriteLine(a);
    }

    class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }

    #endregion
}


using System;
using System.IO;
using System.Linq;
using System.Text;

namespace Phone_Number
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            string s = reader.ReadLine();
            int[] nn = s.ToCharArray().Select(e => e - '0').ToArray();

            var dp = new long[10,nn.Length];
            for (int i = 0; i < 10; i++)
            {
                dp[i, 0] = 1;
            }

            for (int j = 1; j < nn.Length; j++)
            {
                for (int i = 0; i < 10; i++)
                {
                    int ss = i + nn[j];
                    if (ss%2 == 0)
                        dp[ss/2, j] += dp[i, j - 1];
                    else
                    {
                        dp[ss/2, j] += dp[i, j - 1];
                        dp[(ss + 1)/2, j] += dp[i, j - 1];
                    }
                }
            }

            long sum = -1;
            for (int i = 0; i < 10; i++)
            {
                sum += dp[i, nn.Length - 1];
            }
            for (int i = 1; i < nn.Length; i++)
            {
                if (Math.Abs(nn[i] - nn[i - 1]) > 1)
                {
                    sum++;
                    break;
                }
            }

            writer.WriteLine(sum);
            writer.Flush();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProgrammingContest.Codeforces.SchoolTeam2
{
    class H
    {
        public static void Main()
        {
            string s = Console.ReadLine();
            int n = s.Length;
            long[,] dp = new long[n, 10];

            long res = 0;
            bool self = false;
            for (int u = 0; u < 10; u++)
            {
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < 10; j++)
                        dp[i, j] = 0;
                dp[0, u] = 1;
                for (int i = 1; i < n; i++)
                {
                    int x = s[i] - '0';
                    for (int j = 0; j < 10; j++)
                    {
                        int y = j + x;
                        for (int k = 0; k <= y % 2; k++)
                            dp[i, y / 2 + k] += dp[i - 1, j];
                    }
                }
                for (int i = 0; i < 10; i++) res += dp[n - 1, i];

                bool b = true;
                for (int i = 0; i < n; i++) b &= dp[i, s[i] - '0'] > 0;
                self |= b;
            }

            Console.WriteLine(res - (self ? 1 : 0));
        }
    }
}


using System;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            var str = Console.ReadLine();
            var n = Int32.Parse(str);

            var fi = new int[n + 1];
            var used = new int[3 * n];
            var kucha = new int[n + 1];

            for (int i = 3; i <= n; ++i)
            {
                for (int k = 2; k <= 4 * (int)Math.Sqrt(i); ++k)
                {
                    var delta = i - (k*(k - 1))/2;
                    if (delta <= 0)
                        break;

                    if (delta % k != 0)
                        continue;

                    var c = delta/k;
                    var curFi = 0;
                    for (int j = 0; j < k; ++j)
                    {
                        curFi = curFi ^ fi[c + j];
                    }
                    used[curFi] = i;
                    if (curFi == 0 && kucha[i] == 0)
                    {
                        kucha[i] = k;
                    }
                }

                if (kucha[i] > 0)
                {
                    for (int j = 0; j <= n; ++j)
                    {
                        if (used[j] != i)
                        {
                            fi[i] = j;
                            break;
                        }
                    }
                }
            }
            if (fi[n] == 0)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(kucha[n]);
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cs_console
{
    class _73_2_E
    {
        //nim
        //game
        public static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] grundy = new int[n + 1];
            int[] ans = new int[n + 1];
            grundy[1] = 0;
            ans[1] = -1;
            for (int i = 2; i <= n; i++)
            {
                grundy[i] = 0;
                ans[i] = -1;
                bool ok = false;
                Dictionary<int, int> used = new Dictionary<int, int>();
                for (int len = 2; len * (len + 1) / 2 <= i; len++)
                {
                    if (i * 2 % len == 0)
                    {
                        int aa = i * 2 / len - len + 1;
                        if (aa % 2 == 0 && aa > 0)
                        {
                            int x = aa / 2;
                            //valid split (x, x + 1, ..., x + k - 1)
                            int ng = 0;
                            for (int k = 0; k < len; k++)
                            {
                                ng ^= grundy[x + k];
                            }
                            if(!ok && ng == 0)
                            {
                                //good
                                ok = true;
                                ans[i] = len;
                            }
                            used[ng] = 1;
                        }
                    }
                }
                //find the min value not used -- grundy value
                for (int j = 0; ; j++)
                {
                    if (!used.ContainsKey(j))
                    {
                        grundy[i] = j;
                        break;
                    }
                }
                if (!ok)
                {
                    ans[i] = -1;
                }
            }
            //for (int i = 0; i < n; i++)
            //{
            //Console.WriteLine(i + " " + ans[i] + " " + grundy[i]);
            //}
            Console.WriteLine(ans[n]);
        }
    }
}


using System;
using System.Collections.Generic;

namespace CodeForceCs
{
    static class Program
    {
        static void Main(string[] args)
        {
            Solver solver = new _462_2D();
            solver.SolveProblem();
            //Console.ReadKey();
        }
    }

    static class Utility
    {
        static public T[] NewArrayWithValue<T>(int length, T value)
        {
            T[] array = new T[length];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = value;
            }
            return array;
        }
    }

    abstract class Solver
    {
        abstract public void SolveProblem();
    }

    class _462_2D : Solver
    {
        Int64 p, k, z;
        int d;
        List<Int64> a, q;
        String result;
        public override void SolveProblem()
        {
            String[] input = Console.ReadLine().Split();
            p = Int64.Parse(input[0]);
            k = Int64.Parse(input[1]);
            a = new List<Int64>();
            q = new List<Int64>();

            d = 1;
            z = p % k;
            a.Add(z);
            q.Add((z - p) / k);

            while (!(q[d-1] >= 0 && q[d-1] < k))
            {
                z = q[d - 1] % k;
                if (z < 0)
                    z += k;
                a.Add(z);
                q.Add((z - q[d - 1]) / k);
                d++;
            }
            if (q[d - 1] != 0)
            {
                a.Add(q[d - 1]);
                d++;
            }

            Console.WriteLine(d);

            result = "";
            foreach (Int64 v in a)
                result += v + " ";
            Console.WriteLine(result);

            //result = "";
            //foreach (Int64 v in q)
            //    result += v + " ";
            //Console.WriteLine(result);
        }
    }

    class _462_2C : Solver
    {
        List<int> a;
        int n, result;

        public override void SolveProblem()
        {
            a = new List<int>();
            n = int.Parse(Console.ReadLine());
            result = Math.Min(n, 2);

            String[] input = Console.ReadLine().Split();
            foreach (String s in input)
                a.Add(int.Parse(s));

            for (int i = 1; i < n-1; i++)
            {
                result = Math.Max(result, GetMaxNonDec(0, i) + GetMaxNonDec(i, n - i));
            }
            Console.WriteLine(result);

        }

        int GetMaxNonDec(int start, int length)
        {
            if (length <= 0)
                return 0;

            int[] oneNum, twoNum;
            oneNum = new int[length];
            twoNum = new int[length];
            oneNum[0] = a[start] == 1 ? 1 : 0;
            twoNum[0] = a[start + length - 1] == 2 ? 1 : 0;

            for (int i = 1; i < length; i++ )
            {
                oneNum[i] = oneNum[i-1];
                twoNum[i] = twoNum[i-1];
                if (a[start + i] == 1)
                    oneNum[i]++;
                if (a[start + length - 1 - i] == 2)
                    twoNum[i]++;
            }

            int result = Math.Min(length, 2);
            for (int i = 0; i < length; i++)
                result = Math.Max(result, oneNum[i] + twoNum[length - i - 1]);
            return result;
        }
    }

    class _462_2B : Solver
    {
        String result = "";
        int k;
        public override void SolveProblem()
        {
            k = int.Parse(Console.ReadLine());
            if (k > 36)
            {
                Console.WriteLine("-1");
                return;
            }
            while (k > 1)
            {
                result += "8";
                k -= 2;
            }
            if (k == 1)
                result += "6";
            Console.WriteLine(result);
        }
    }

    class _462_2A : Solver
    {
        int n, m;
        List<Int64> a, b;
        Int64 result;
        public override void SolveProblem()
        {
            a = new List<Int64>();
            b = new List<Int64>();

            String[] input = Console.ReadLine().Split();
            n = int.Parse(input[0]);
            m = int.Parse(input[1]);

            input = Console.ReadLine().Split();
            foreach (String s in input)
                a.Add(Int64.Parse(s));

            input = Console.ReadLine().Split();
            foreach (String s in input)
                b.Add(Int64.Parse(s));

            a.Sort();
            b.Sort();

            Int64 p11, p12, p21, p22;
            p11 = Math.Max(a[1] * b[0], a[1] * b[m-1]);
            p12 = Math.Max(a[n - 1] * b[0], a[n - 1] * b[m - 1]);
            p21 = Math.Max(a[0] * b[0], a[0] * b[m - 1]);
            p22 = Math.Max(a[n - 2] * b[0], a[n - 2] * b[m - 1]);

            result = Math.Min(Math.Max(p11, p12), Math.Max(p21, p22));

            Console.WriteLine(result);
        }
    }

    class _910A : Solver
    {
        int n, d;
        int[] minstep;
        string lily;
        override public void SolveProblem()
        {
            var input = Console.ReadLine().Split();
            n = int.Parse(input[0]);
            d = int.Parse(input[1]);
            lily = Console.ReadLine();
            minstep = Utility.NewArrayWithValue<int>(n+1, 999);
            minstep[1] = 0;

            for (int i = 2; i <= n; i++)
            {
                for (int j = i; j >= Math.Max(1, i-d); j--)
                {
                    if (lily[j-1] == '0')
                        continue;

                    minstep[i] = Math.Min(minstep[i], minstep[j] + 1);
                }
            }

            if (minstep[n] > n)
                Console.WriteLine(-1);
            else
                Console.WriteLine(minstep[n]);
        }

    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;

class Myon
{
    public Myon() { }
    public static int Main()
    {
        new Myon().calc();
        return 0;
    }

    Scanner cin;

    void calc()
    {
        cin = new Scanner();
        long p = cin.nextLong();
        long k = cin.nextLong();

        long now = p;
        List<long> ans = new List<long>();
        while (now < 0 || now >= k)
        {
            if (ans.Count >= 1000000) break;
            long mul;
            if (now > 0) mul = now / k;
            else mul = -((-now + (k - 1)) / k);
            now -= mul * k;
            ans.Add(now);
            now = -mul;
        }
        if(ans.Count >= 1000000)
        {
            Console.WriteLine(-1);
            return;
        }
        ans.Add(now);

        Console.WriteLine(ans.Count);
        Console.WriteLine(string.Join(" ", ans));
    }

}

class Scanner
{
    string[] s;
    int i;

    char[] cs = new char[] { ' ' };

    public Scanner()
    {
        s = new string[0];
        i = 0;
    }

    public string next()
    {
        if (i < s.Length) return s[i++];
        string st = Console.ReadLine();
        while (st == "") st = Console.ReadLine();
        s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
        if (s.Length == 0) return next();
        i = 0;
        return s[i++];
    }

    public int nextInt()
    {
        return int.Parse(next());
    }
    public int[] ArrayInt(int N, int add = 0)
    {
        int[] Array = new int[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextInt() + add;
        }
        return Array;
    }

    public long nextLong()
    {
        return long.Parse(next());
    }

    public long[] ArrayLong(int N, long add = 0)
    {
        long[] Array = new long[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextLong() + add;
        }
        return Array;
    }

    public double nextDouble()
    {
        return double.Parse(next());
    }

    public double[] ArrayDouble(int N, double add = 0)
    {
        double[] Array = new double[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextDouble() + add;
        }
        return Array;
    }
}


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace ReadWriteTemplate
{
    public static class Solver
    {
        private static void SolveCase()
        {
            const long MOD = 998244353;

            var ntt = new NTTFastLong(MOD);

            int n = ReadInt();
            int k = ReadInt();
            int[] d = ReadIntArray();

            int m = 1;
            int p = 0;
            while (m < 5 * n)
            {
                m <<= 1;
                p++;
            }

            long[] a = new long[m];
            for (int i = 0; i < k; i++)
            {
                a[d[i]] = 1;
            }

            ntt.FFT(a);

            for (int i = 0; i < m; i++)
            {
                a[i] = ntt.Power(a[i], n / 2);
            }

            ntt.FFT(a);

            long invM = ntt.Inv(m);

            long ans = 0;
            for (int i = 0; i < a.Length; i++)
            {
                long c = a[i] * invM % MOD;
                ans = (ans + c * c) % MOD;
            }

            Writer.WriteLine(ans);
        }

        public class NTTFastLong
        {
            private int curBase = 1;
            private long[] roots = { 0, 1 };
            private int[] rev = { 0, 1 };
            private int maxBase = -1;
            private int root = -1;

            private readonly long MOD;

            public NTTFastLong(long mod)
            {
                MOD = mod;
            }

            private void Init()
            {
                long tmp = MOD - 1;
                maxBase = 0;
                while (tmp % 2 == 0)
                {
                    tmp /= 2;
                    maxBase++;
                }
                root = 2;
                while (true)
                {
                    if (Power(root, 1 << maxBase) == 1)
                    {
                        if (Power(root, 1 << (maxBase - 1)) != 1)
                        {
                            break;
                        }
                    }
                    root++;
                }
            }

            void ensure_base(int nBase)
            {
                if (maxBase == -1)
                {
                    Init();
                }
                if (nBase <= curBase)
                {
                    return;
                }
                if (nBase > maxBase)
                {
                    throw new InvalidOperationException();
                }
                Array.Resize(ref rev, 1 << nBase);
                for (int i = 0; i < (1 << nBase); i++)
                {
                    rev[i] = (rev[i >> 1] >> 1) + ((i & 1) << (nBase - 1));
                }
                Array.Resize(ref roots, 1 << nBase);
                while (curBase < nBase)
                {
                    long z = Power(root, 1 << (maxBase - 1 - curBase));
                    for (int i = 1 << (curBase - 1); i < (1 << curBase); i++)
                    {
                        roots[i << 1] = roots[i];
                        roots[(i << 1) + 1] = roots[i] * z % MOD;
                    }
                    curBase++;
                }
            }

            public void FFT(long[] a)
            {
                int n = a.Length;
                if ((n & (n - 1)) != 0)
                {
                    throw new InvalidOperationException();
                }
                int zeros = get__builtin_ctz(n);
                ensure_base(zeros);
                int shift = curBase - zeros;
                for (int i = 0; i < n; i++)
                {
                    if (i < (rev[i] >> shift))
                    {
                        long tmp = a[i];
                        a[i] = a[rev[i] >> shift];
                        a[rev[i] >> shift] = tmp;
                    }
                }
                for (int k = 1; k < n; k <<= 1)
                {
                    for (int i = 0; i < n; i += 2 * k)
                    {
                        for (int j = 0; j < k; j++)
                        {
                            long x = a[i + j];
                            long y = a[i + j + k] * roots[j + k] % MOD;
                            a[i + j] = x + y - MOD;
                            if (a[i + j] < 0)
                            {
                                a[i + j] += MOD;
                            }
                            a[i + j + k] = x - y + MOD;
                            if (a[i + j + k] >= MOD)
                            {
                                a[i + j + k] -= MOD;
                            }
                        }
                    }
                }
            }

            // todo: rename? remove?
            private int get__builtin_ctz(int n)
            {
                int c = 0;
                while (n > 0 && (n & 1) == 0)
                {
                    c++;
                    n >>= 1;
                }
                return c;
            }

            public long[] Multiply(long[] a, long[] b, int eq = 0)
            {
                int need = a.Length + b.Length - 1;
                int nbase = 0;
                while ((1 << nbase) < need)
                {
                    nbase++;
                }
                ensure_base(nbase);
                int sz = 1 << nbase;
                Array.Resize(ref a, sz);
                Array.Resize(ref b, sz);
                FFT(a);
                if (eq != 0)
                {
                    b = a;
                }
                else
                {
                    FFT(b);
                }
                long invSz = Inv(sz);
                for (int i = 0; i < sz; i++)
                {
                    a[i] = a[i] * b[i] % MOD * invSz % MOD;
                }
                Array.Reverse(a, 1, a.Length - 1);
                FFT(a);

                int newSize = need;
                while (newSize > 0 && a[newSize - 1] == 0)
                {
                    newSize--;
                }
                Array.Resize(ref a, newSize);

                return a;
            }

            public long[] Square(long[] a)
            {
                return Multiply(a, a, 1);
            }

            public long Power(long a, long b)
            {
                long res = 1;
                while (b > 0)
                {
                    if ((b & 1) > 0)
                    {
                        res = res * a % MOD;
                    }
                    a = a * a % MOD;
                    b >>= 1;
                }
                return res;
            }

            public long Inv(long a)
            {
                a %= MOD;
                if (a < 0)
                {
                    a += MOD;
                }
                long b = MOD;
                long u = 0;
                long v = 1;
                while (a != 0)
                {
                    long t = b / a;
                    b -= t * a;

                    long tmp = a;
                    a = b;
                    b = tmp;

                    u -= t * v;

                    tmp = u;
                    u = v;
                    v = tmp;
                }
                if (u < 0)
                {
                    u += MOD;
                }
                return u;
            }
        }

        public static void Solve()
        {
#if DEBUG
            var sw = Stopwatch.StartNew();
#endif

            SolveCase();

            /*int T = ReadInt();
            for (int i = 0; i < T; i++)
            {
                Writer.Write("Case #{0}: ", i + 1);
                SolveCase();
            }*/

#if DEBUG
            sw.Stop();
            Console.WriteLine($"{sw.ElapsedMilliseconds} ms");
#endif
        }

        public static void Main()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

#if DEBUG
            //Reader = Console.In; Writer = Console.Out;
            Reader = File.OpenText("input.txt"); Writer = File.CreateText("output.txt");
#else
            Reader = Console.In; Writer = Console.Out;
#endif

            // Solve();
            Thread thread = new Thread(Solve, 64 * 1024 * 1024);
            thread.CurrentCulture = CultureInfo.InvariantCulture;
            thread.Start();
            thread.Join();

            Reader.Close();
            Writer.Close();
        }

        public static IOrderedEnumerable<TSource> OrderByWithShuffle<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            return source.Shuffle().OrderBy(keySelector);
        }

        public static T[] Shuffle<T>(this IEnumerable<T> source)
        {
            T[] result = source.ToArray();
            Random rnd = new Random();
            for (int i = result.Length - 1; i >= 1; i--)
            {
                int k = rnd.Next(i + 1);
                T tmp = result[k];
                result[k] = result[i];
                result[i] = tmp;
            }
            return result;
        }

        #region Read/Write

        private static TextReader Reader;

        private static TextWriter Writer;

        private static Queue<string> CurrentLineTokens = new Queue<string>();

        private static string[] ReadAndSplitLine()
        {
            return Reader.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        }

        public static string ReadToken()
        {
            while (CurrentLineTokens.Count == 0)
                CurrentLineTokens = new Queue<string>(ReadAndSplitLine());
            return CurrentLineTokens.Dequeue();
        }

        public static string ReadLine()
        {
            return Reader.ReadLine();
        }

        public static int ReadInt()
        {
            return int.Parse(ReadToken());
        }

        public static long ReadLong()
        {
            return long.Parse(ReadToken());
        }

        public static double ReadDouble()
        {
            return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
        }

        public static int[] ReadIntArray()
        {
            return ReadAndSplitLine().Select(int.Parse).ToArray();
        }

        public static long[] ReadLongArray()
        {
            return ReadAndSplitLine().Select(long.Parse).ToArray();
        }

        public static double[] ReadDoubleArray()
        {
            return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
        }

        public static int[][] ReadIntMatrix(int numberOfRows)
        {
            int[][] matrix = new int[numberOfRows][];
            for (int i = 0; i < numberOfRows; i++)
                matrix[i] = ReadIntArray();
            return matrix;
        }

        public static string[] ReadLines(int quantity)
        {
            string[] lines = new string[quantity];
            for (int i = 0; i < quantity; i++)
                lines[i] = Reader.ReadLine().Trim();
            return lines;
        }

        public static void WriteArray<T>(IEnumerable<T> array)
        {
            Writer.WriteLine(string.Join(" ", array));
        }

        #endregion
    }
}


using System;
using System.Collections.Generic;
using System.Diagnostics;
using CompLib.Mathematics;
using CompLib.Util;

public class Program
{
    private const int MaxLg = 21;

    private int N, K;

    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        K = sc.NextInt();

        ModInt[] a = new ModInt[1 << MaxLg];
        a[0] = 1;

        ModInt[] b = new ModInt[1 << MaxLg];
        int min = int.MaxValue;
        int max = int.MinValue;
        for (int i = 0; i < K; i++)
        {
            int d = sc.NextInt();
            min = Math.Min(min, d);
            max = Math.Max(max, d);
            b[d] = 1;
        }

        int lenA = 1;
        int lenB = max + 1;

        int h = N / 2;
        int tmp = h;
        while (tmp > 0)
        {
            if ((tmp & 1) > 0)
            {
                FFT.Convolusion(ref a, lenA, b, lenB);
                lenA = lenA + lenB - 1;
            }

            if (tmp > 1)
            {
                FFT.Convolusion(ref b, lenB);
                lenB = lenB + lenB - 1;
            }

            tmp /= 2;
        }

        ModInt ans = 0;
        for (int i = min * h; i <= max * h; i++)
        {
            ans += a[i] * a[i];
        }

        Console.WriteLine(ans);
    }

    public static void Main(string[] args) => new Program().Solve();
}

static class FFT
{
    private const int E = 23;
    private const int MaxLg = 21;
    private static readonly ModInt O = 31;

    private static readonly ModInt[] Z, InvZ;

    private static readonly List<(int f, int t)>[] Rev;
    private static readonly ModInt[] InvLen;

    static FFT()
    {
        Z = new ModInt[E + 1];
        InvZ = new ModInt[E + 1];
        Z[E] = O;
        InvZ[E] = ModInt.Inverse(O);

        for (int i = E - 1; i >= 0; i--)
        {
            Z[i] = Z[i + 1] * Z[i + 1];
            InvZ[i] = InvZ[i + 1] * InvZ[i + 1];
        }

        Rev = new List<(int f, int t)>[MaxLg + 1];
        for (int i = 0; i <= MaxLg; i++)
        {
            int len = 1 << i;
            Rev[i] = new List<(int f, int t)>();
            for (int j = 0; j < len; j++)
            {
                int r = BitsReverse(j, i);
                if (j < r) Rev[i].Add((j, r));
            }
        }

        InvLen = new ModInt[MaxLg + 1];
        for (int i = 0; i <= MaxLg; i++)
        {
            InvLen[i] = ModInt.Inverse(1 << i);
        }
    }

    public static void Transform(ModInt[] a, int lg, int len, bool inverse)
    {
        foreach (var pair in Rev[lg])
        {
            var t = a[pair.f];
            a[pair.f] = a[pair.t];
            a[pair.t] = t;
        }

        for (int i = 1; i <= lg; i++)
        {
            int b = 1 << (i - 1);
            ModInt z = 1;
            for (int j = 0; j < b; j++)
            {
                for (int k = j; k < len; k += (b << 1))
                {
                    var t = z * a[k + b];
                    var u = a[k];
                    a[k] = u + t;
                    a[k + b] = u - t;
                }

                z *= inverse ? InvZ[i] : Z[i];
            }
        }
    }

    public static void Convolusion(ref ModInt[] a, int lenA, ModInt[] b, int lenB)
    {
        int sz = lenA + lenB - 1;
        int len = 1;
        int lg = 0;
        while (len < sz)
        {
            len <<= 1;
            lg++;
        }

        Transform(a, lg, len, false);
        var tmpB = new ModInt[len];
        Array.Copy(b, tmpB, len);
        Transform(tmpB, lg, len, false);
        for (int i = 0; i < len; i++)
        {
            a[i] *= tmpB[i];
        }

        Transform(a, lg, len, true);
        for (int i = 0; i < sz; i++)
        {
            a[i] *= InvLen[lg];
        }
    }

    public static void Convolusion(ref ModInt[] a, int lenA)
    {
        int sz = lenA * 2 - 1;
        int len = 1;
        int lg = 0;
        while (len < sz)
        {
            len <<= 1;
            lg++;
        }

        Transform(a, lg, len, false);
        for (int i = 0; i < len; i++)
        {
            a[i] *= a[i];
        }

        Transform(a, lg, len, true);
        for (int i = 0; i < sz; i++)
        {
            a[i] *= InvLen[lg];
        }
    }

    private static int BitsReverse(int v, int lg)
    {
        if (v == 0) return v;
        int r = 0;
        if (lg % 2 == 1) r |= v & (1 << (lg / 2));
        for (int i = 0; i < lg / 2; i++)
        {
            r |= ((v >> i) & 1) << (lg - i - 1);
            r |= ((v >> (lg - i - 1)) & 1) << i;
        }

        return r;
    }
}

// https://bitbucket.org/camypaper/complib
namespace CompLib.Mathematics
{
    #region ModInt

    /// <summary>
    /// [0,<see cref="Mod"/>) までの値を取るような数
    /// </summary>
    public struct ModInt
    {
        /// <summary>
        /// 剰余を取る値．
        /// </summary>
        public const long Mod = 998244353;

        /// <summary>
        /// 実際の数値．
        /// </summary>
        public long num;

        /// <summary>
        /// 値が <paramref name="n"/> であるようなインスタンスを構築します．
        /// </summary>
        /// <param name="n">インスタンスが持つ値</param>
        /// <remarks>パフォーマンスの問題上，コンストラクタ内では剰余を取りません．そのため，<paramref name="n"/> ∈ [0,<see cref="Mod"/>) を満たすような <paramref name="n"/> を渡してください．このコンストラクタは O(1) で実行されます．</remarks>
        public ModInt(long n)
        {
            num = n;
        }

        /// <summary>
        /// このインスタンスの数値を文字列に変換します．
        /// </summary>
        /// <returns>[0,<see cref="Mod"/>) の範囲内の整数を 10 進表記したもの．</returns>
        public override string ToString()
        {
            return num.ToString();
        }

        public static ModInt operator +(ModInt l, ModInt r)
        {
            l.num += r.num;
            if (l.num >= Mod) l.num -= Mod;
            return l;
        }

        public static ModInt operator -(ModInt l, ModInt r)
        {
            l.num -= r.num;
            if (l.num < 0) l.num += Mod;
            return l;
        }

        public static ModInt operator *(ModInt l, ModInt r)
        {
            return new ModInt(l.num * r.num % Mod);
        }

        public static implicit operator ModInt(long n)
        {
            n %= Mod;
            if (n < 0) n += Mod;
            return new ModInt(n);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(ModInt v, long k)
        {
            return Pow(v.num, k);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(long v, long k)
        {
            long ret = 1;
            for (k %= Mod - 1; k > 0; k >>= 1, v = v * v % Mod)
                if ((k & 1) == 1)
                    ret = ret * v % Mod;
            return new ModInt(ret);
        }

        /// <summary>
        /// 与えられた数の逆元を計算します．
        /// </summary>
        /// <param name="v">逆元を取る対象となる数</param>
        /// <returns>逆元となるような値</returns>
        /// <remarks>法が素数であることを仮定して，フェルマーの小定理に従って逆元を O(log N) で計算します．</remarks>
        public static ModInt Inverse(ModInt v)
        {
            return Pow(v, Mod - 2);
        }
    }

    #endregion

    #region Binomial Coefficient

    public class BinomialCoefficient
    {
        public ModInt[] fact, ifact;

        public BinomialCoefficient(int n)
        {
            fact = new ModInt[n + 1];
            ifact = new ModInt[n + 1];
            fact[0] = 1;
            for (int i = 1; i <= n; i++)
                fact[i] = fact[i - 1] * i;
            ifact[n] = ModInt.Inverse(fact[n]);
            for (int i = n - 1; i >= 0; i--)
                ifact[i] = ifact[i + 1] * (i + 1);
            ifact[0] = ifact[1];
        }

        public ModInt this[int n, int r]
        {
            get
            {
                if (n < 0 || n >= fact.Length || r < 0 || r > n) return 0;
                return fact[n] * ifact[n - r] * ifact[r];
            }
        }

        public ModInt RepeatedCombination(int n, int k)
        {
            if (k == 0) return 1;
            return this[n + k - 1, k];
        }
    }

    #endregion
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s = Console.ReadLine();
                while (s.Length == 0)
                {
                    s = Console.ReadLine();
                }

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Collections.Generic;
using System.Diagnostics;
using CompLib.Mathematics;
using CompLib.Util;

public class Program
{
    private const int MaxLg = 20;

    private int N, K;

    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        K = sc.NextInt();

        ModInt[] a = new ModInt[1 << MaxLg];
        a[0] = 1;

        ModInt[] b = new ModInt[1 << MaxLg];
        int min = int.MaxValue;
        int max = int.MinValue;
        for (int i = 0; i < K; i++)
        {
            int d = sc.NextInt();
            min = Math.Min(min, d);
            max = Math.Max(max, d);
            b[d] = 1;
        }

        int lenA = 1;
        int lenB = max + 1;

        int h = N / 2;
        int tmp = h;
        while (tmp > 0)
        {
            if ((tmp & 1) > 0)
            {
                FFT.Convolusion(ref a, lenA, b, lenB);
                lenA = lenA + lenB - 1;
            }

            if (tmp > 1)
            {
                FFT.Convolusion(ref b, lenB);
                lenB = lenB + lenB - 1;
            }

            tmp /= 2;
        }

        ModInt ans = 0;
        for (int i = min * h; i <= max * h; i++)
        {
            ans += a[i] * a[i];
        }

        Console.WriteLine(ans);
    }

    public static void Main(string[] args) => new Program().Solve();
}

static class FFT
{
    private const int E = 23;
    private const int MaxLg = 20;
    private static readonly ModInt O = 31;

    private static readonly ModInt[] Z, InvZ;

    private static readonly List<(int f, int t)>[] Rev;
    private static readonly ModInt[] InvLen;

    static FFT()
    {
        Z = new ModInt[E + 1];
        InvZ = new ModInt[E + 1];
        Z[E] = O;
        InvZ[E] = ModInt.Inverse(O);

        for (int i = E - 1; i >= 0; i--)
        {
            Z[i] = Z[i + 1] * Z[i + 1];
            InvZ[i] = InvZ[i + 1] * InvZ[i + 1];
        }

        Rev = new List<(int f, int t)>[MaxLg + 1];
        for (int i = 0; i <= MaxLg; i++)
        {
            int len = 1 << i;
            Rev[i] = new List<(int f, int t)>();
            for (int j = 0; j < len; j++)
            {
                int r = BitsReverse(j, i);
                if (j < r) Rev[i].Add((j, r));
            }
        }

        InvLen = new ModInt[MaxLg + 1];
        for (int i = 0; i <= MaxLg; i++)
        {
            InvLen[i] = ModInt.Inverse(1 << i);
        }
    }

    public static void Transform(ModInt[] a, int lg, int len, bool inverse)
    {
        foreach (var pair in Rev[lg])
        {
            var t = a[pair.f];
            a[pair.f] = a[pair.t];
            a[pair.t] = t;
        }

        for (int i = 1; i <= lg; i++)
        {
            int b = 1 << (i - 1);
            ModInt z = 1;
            for (int j = 0; j < b; j++)
            {
                for (int k = j; k < len; k += (b << 1))
                {
                    var t = z * a[k + b];
                    var u = a[k];
                    a[k] = u + t;
                    a[k + b] = u - t;
                }

                z *= inverse ? InvZ[i] : Z[i];
            }
        }
    }

    public static void Convolusion(ref ModInt[] a, int lenA, ModInt[] b, int lenB)
    {
        int sz = lenA + lenB - 1;
        int len = 1;
        int lg = 0;
        while (len < sz)
        {
            len <<= 1;
            lg++;
        }

        Transform(a, lg, len, false);
        var tmpB = new ModInt[len];
        Array.Copy(b, tmpB, len);
        Transform(tmpB, lg, len, false);
        for (int i = 0; i < len; i++)
        {
            a[i] *= tmpB[i];
        }

        Transform(a, lg, len, true);
        for (int i = 0; i < sz; i++)
        {
            a[i] *= InvLen[lg];
        }
    }

    public static void Convolusion(ref ModInt[] a, int lenA)
    {
        int sz = lenA * 2 - 1;
        int len = 1;
        int lg = 0;
        while (len < sz)
        {
            len <<= 1;
            lg++;
        }

        Transform(a, lg, len, false);
        for (int i = 0; i < len; i++)
        {
            a[i] *= a[i];
        }

        Transform(a, lg, len, true);
        for (int i = 0; i < sz; i++)
        {
            a[i] *= InvLen[lg];
        }
    }

    private static int BitsReverse(int v, int lg)
    {
        if (v == 0) return v;
        int r = 0;
        if (lg % 2 == 1) r |= v & (1 << (lg / 2));
        for (int i = 0; i < lg / 2; i++)
        {
            r |= ((v >> i) & 1) << (lg - i - 1);
            r |= ((v >> (lg - i - 1)) & 1) << i;
        }

        return r;
    }
}

// https://bitbucket.org/camypaper/complib
namespace CompLib.Mathematics
{
    #region ModInt

    /// <summary>
    /// [0,<see cref="Mod"/>) までの値を取るような数
    /// </summary>
    public struct ModInt
    {
        /// <summary>
        /// 剰余を取る値．
        /// </summary>
        public const long Mod = 998244353;

        /// <summary>
        /// 実際の数値．
        /// </summary>
        public long num;

        /// <summary>
        /// 値が <paramref name="n"/> であるようなインスタンスを構築します．
        /// </summary>
        /// <param name="n">インスタンスが持つ値</param>
        /// <remarks>パフォーマンスの問題上，コンストラクタ内では剰余を取りません．そのため，<paramref name="n"/> ∈ [0,<see cref="Mod"/>) を満たすような <paramref name="n"/> を渡してください．このコンストラクタは O(1) で実行されます．</remarks>
        public ModInt(long n)
        {
            num = n;
        }

        /// <summary>
        /// このインスタンスの数値を文字列に変換します．
        /// </summary>
        /// <returns>[0,<see cref="Mod"/>) の範囲内の整数を 10 進表記したもの．</returns>
        public override string ToString()
        {
            return num.ToString();
        }

        public static ModInt operator +(ModInt l, ModInt r)
        {
            l.num += r.num;
            if (l.num >= Mod) l.num -= Mod;
            return l;
        }

        public static ModInt operator -(ModInt l, ModInt r)
        {
            l.num -= r.num;
            if (l.num < 0) l.num += Mod;
            return l;
        }

        public static ModInt operator *(ModInt l, ModInt r)
        {
            return new ModInt(l.num * r.num % Mod);
        }

        public static implicit operator ModInt(long n)
        {
            n %= Mod;
            if (n < 0) n += Mod;
            return new ModInt(n);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(ModInt v, long k)
        {
            return Pow(v.num, k);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(long v, long k)
        {
            long ret = 1;
            for (k %= Mod - 1; k > 0; k >>= 1, v = v * v % Mod)
                if ((k & 1) == 1)
                    ret = ret * v % Mod;
            return new ModInt(ret);
        }

        /// <summary>
        /// 与えられた数の逆元を計算します．
        /// </summary>
        /// <param name="v">逆元を取る対象となる数</param>
        /// <returns>逆元となるような値</returns>
        /// <remarks>法が素数であることを仮定して，フェルマーの小定理に従って逆元を O(log N) で計算します．</remarks>
        public static ModInt Inverse(ModInt v)
        {
            return Pow(v, Mod - 2);
        }
    }

    #endregion

    #region Binomial Coefficient

    public class BinomialCoefficient
    {
        public ModInt[] fact, ifact;

        public BinomialCoefficient(int n)
        {
            fact = new ModInt[n + 1];
            ifact = new ModInt[n + 1];
            fact[0] = 1;
            for (int i = 1; i <= n; i++)
                fact[i] = fact[i - 1] * i;
            ifact[n] = ModInt.Inverse(fact[n]);
            for (int i = n - 1; i >= 0; i--)
                ifact[i] = ifact[i + 1] * (i + 1);
            ifact[0] = ifact[1];
        }

        public ModInt this[int n, int r]
        {
            get
            {
                if (n < 0 || n >= fact.Length || r < 0 || r > n) return 0;
                return fact[n] * ifact[n - r] * ifact[r];
            }
        }

        public ModInt RepeatedCombination(int n, int k)
        {
            if (k == 0) return 1;
            return this[n + k - 1, k];
        }
    }

    #endregion
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s = Console.ReadLine();
                while (s.Length == 0)
                {
                    s = Console.ReadLine();
                }

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using Math = System.Math;
using Dec = System.Decimal;
using System.Globalization;
using System.Linq;

namespace taskA
{
	class newDecimal {
	private
			Int64 Z, F, kol;
	public newDecimal(decimal t, Int64 Kol) {
			kol = Kol;
			Z = Dec.ToInt64 (t);
			Int64 p = 1;
			for (int i = 0; i < kol; i ++)
				p *= 10L;
			F = Dec.ToInt64 ((t - Z) * p);
		}
		public void print () {
			Console.Write ("{0}.", Z);
			int sz = F.ToString ().Length;
			for (int i = 0; i < kol - sz; i ++)
				Console.Write (0);
			Console.Write (F);
		}
	}

	class MainClass
	{
		public static long[,] C = new long[800, 10];

		public static void PreCalc() {
			C [1,1] = 1L;
			C [2,1] = 2L;
			C [2,2] = 1L;
			for (int i = 3; i <= 777; i ++) C[i,1] = 1L*i;
			for (int i = 3; i <= 777; i ++)
				for (int j = 2; j <= 7; j ++)
					C [i,j] = C [i - 1,j] + C [i - 1,j - 1];
		}

		public static void Main(string[] args) {
			PreCalc ();
			int n = int.Parse (Console.ReadLine ());
			long ans = 0l;

			ans += 4l * 3l * 2l * (1l << ((n - 3) << 1));
			if (n >= 4)
				ans += 3L * 3L * (n - 3L) * (1L << (2 * (n - 3)));
			Console.WriteLine (ans);
		}
	}
}


using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace codeforces
{
    public class Program
    {
        private static void Main(string[] args)
        {
            ulong result = 0;
            int n = Convert.ToInt32(Console.ReadLine());
            int m = 2 * n - 2;
            for (int i = 0; i < m - n + 1; ++i)
            {
                int l = i;
                int r = i + n;
                ulong value = 4ul * (l == 0 ? 1ul : 3ul) * (r == m ? 1ul : 3ul);
                int cnt = m - n - (l == 0 ? 0 : 1) - (r == m ? 0 : 1);
                while (cnt > 0)
                {
                    value *= 4ul;
                    cnt--;
                }
                result += value;
            }
            Console.WriteLine(result);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using CompLib.Util;
using System.Threading;

public class Program
{
    private long N, K;

    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextLong();
        K = sc.NextLong();

        /*
         * f(x) = x/2 if x is even
         *      = x-1 otherwise
         *
         *
         * y 偶数 上位桁 y, y+1に一致
         *
         *   奇数 yに一致
         */

        // 最大候補

        // 偶数になるまで (N/(2^i),(N/2^i)-1)

        List<long> x = new List<long>();

        long tmpX = N;
        while (tmpX > 0)
        {
            if (tmpX % 2 == 1)
            {
                x.Add(tmpX);
                if (tmpX - 1 > 0)
                    x.Add(tmpX - 1);
                tmpX /= 2;
            }
            else
            {
                x.Add(tmpX);
                if (tmpX - 2 > 0)
                    x.Add(tmpX - 2);
                tmpX /= 2;
                if (tmpX % 2 == 1 && tmpX > 1) tmpX--;
            }
        }

        foreach (long l in x)
        {
            if (Calc(l) >= K)
            {
                Console.WriteLine(l);
                return;
            }
        }
    }

    long Calc(long x)
    {
        long ans = 0;
        long tmpX = x;
        long p = 1;
        while (tmpX <= N)
        {
            ans += Math.Min(p, N - tmpX + 1);
            p *= 2;
            tmpX *= 2;
        }

        if (x % 2 == 0)
        {
            tmpX = x + 1;
            p = 1;
            while (tmpX <= N)
            {
                ans += Math.Min(p, N - tmpX + 1);
                p *= 2;
                tmpX *= 2;
            }
        }

        return ans;
    }

    public static void Main(string[] args) => new Program().Solve();
    // public static void Main(string[] args) => new Thread(new Program().Solve, 1 << 27).Start();
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s;
                do
                {
                    s = Console.ReadLine();
                } while (s.Length == 0);

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public string ReadLine()
        {
            _index = _line.Length;
            return Console.ReadLine();
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using Debug = System.Diagnostics.Trace;
using SB = System.Text.StringBuilder;
using static System.Math;
using Number = System.Int32;
using System.Numerics;

namespace Program {
	public class Solver {
		Random rnd = new Random();
		public void Solve() {
			var n = rl; var k = rl;
			var max = 1L;
			{
				var l = 0L; var r = n * 2;
				while (r - l > 2) {
					var m = (l + r) / 2;
					if (m % 2 == 1) m--;
					if (f(m, n) + f(m + 1, n) >= k) l = m;
					else r = m;
				}
				max = l;
			}
			Debug.WriteLine(max);
			{
				var l = 1L; var r = n * 2 + 1;
				while (r - l > 2) {
					var m = (l + r) / 2;
					if (m % 2 == 0) m--;
					if (f(m, n) >= k) l = m;
					else r = m;
				}
				max = Max(max, l);
			}
			Console.WriteLine(max);

		}
		long f(long n, long max) {
			if (n == 0) return 0;
			var ini = n;
			var ret = 0L;
			var ma = 0L;
			for (int i = 0; i < 60; i++) {
				if (max < n) break;
				else if (max >= n + ma) {
					ret += ma + 1;
				}
				else {
					ret += max - n + 1;
				}
				n *= 2;
				ma = ma * 2 + 1;
			}
			Debug.WriteLine($"f({ini},{max}) = {ret}");
			return ret;
		}

		const long INF = 1L << 60;
		static int[] dx = { -1, 0, 1, 0 };
		static int[] dy = { 0, 1, 0, -1 };
		int ri { get { return sc.Integer(); } }
		long rl { get { return sc.Long(); } }
		double rd { get { return sc.Double(); } }
		string rs { get { return sc.Scan(); } }
		public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());

		static T[] Enumerate<T>(int n, Func<int, T> f) {
			var a = new T[n];
			for (int i = 0; i < a.Length; ++i) a[i] = f(i);
			return a;
		}
		static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
	}
}

#region main
static class Ex {
	static public string AsString(this IEnumerable<char> ie) { return new string(ie.ToArray()); }
	static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") {
		return string.Join(st, ie);
	}
	static public void Main() {
		Console.SetOut(new Program.IO.Printer(Console.OpenStandardOutput()) { AutoFlush = true });
		var solver = new Program.Solver();
		//*
		var t = new System.Threading.Thread(solver.Solve, 50000000);
		t.Start();
		t.Join();
		//*/
		// solver.Solve();
		Console.Out.Flush();
	}
}
#endregion
#region Ex
namespace Program.IO {
	using System.IO;
	using System.Text;
	using System.Globalization;

	public class Printer : StreamWriter {
		public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
		public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { }
	}

	public class StreamScanner {
		public StreamScanner(Stream stream) { str = stream; }

		public readonly Stream str;
		private readonly byte[] buf = new byte[1024];
		private int len, ptr;
		public bool isEof = false;
		public bool IsEndOfStream { get { return isEof; } }

		private byte read() {
			if (isEof) return 0;
			if (ptr >= len) {
				ptr = 0;
				if ((len = str.Read(buf, 0, 1024)) <= 0) {
					isEof = true;
					return 0;
				}
			}
			return buf[ptr++];
		}

		public char Char() {
			byte b = 0;
			do b = read(); while ((b < 33 || 126 < b) && !isEof);
			return (char)b;
		}
		public string Scan() {
			var sb = new StringBuilder();
			for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b);
			return sb.ToString();
		}
		public string ScanLine() {
			var sb = new StringBuilder();
			for (var b = Char(); b != '\n' && b != 0; b = (char)read()) if (b != '\r') sb.Append(b);
			return sb.ToString();
		}
		public long Long() { return isEof ? long.MinValue : long.Parse(Scan()); }
		public int Integer() { return isEof ? int.MinValue : int.Parse(Scan()); }
		public double Double() { return isEof ? double.NaN : double.Parse(Scan(), CultureInfo.InvariantCulture); }
	}
}

#endregion


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Heidi_and_Library__easy_
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            int n = Next();
            int k = Next();

            var nn = new int[n];
            for (int i = 0; i < n; i++)
            {
                nn[i] = Next();
            }

            var near = new int[n];
            var last = new int[n + 1];

            for (int i = 0; i < last.Length; i++)
            {
                last[i] = n;
            }

            for (int i = n - 1; i >= 0; i--)
            {
                near[i] = last[nn[i]];
                last[nn[i]] = i;
            }

            int count = 0;
            var heap = new MaxBinaryHeapObject<Point>(new Point());
            var f = new bool[n + 1];
            for (int i = 0; i < nn.Length; i++)
            {
                if (k <= 0 && !f[nn[i]])
                {
                    remove:
                    var t = heap.GetMax();
                    if (!f[t.index])
                    {
                        goto remove;
                    }

                    f[t.index] = false;
                }

                if (!f[nn[i]])
                {
                    count++;
                    f[nn[i]] = true;
                    k--;
                }
                heap.Add(new Point {index = nn[i], near = near[i]});
            }

            writer.WriteLine(count);
            writer.Flush();
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }

        #region Nested type: MaxBinaryHeapObject

        public class MaxBinaryHeapObject<T>
        {
            private readonly IComparer<T> _comparer;
            private readonly List<T> _list;

            public MaxBinaryHeapObject(IComparer<T> comparer)
            {
                _comparer = comparer ?? Comparer<T>.Default;
                _list = new List<T>();
            }

            public int HeapSize
            {
                get { return _list.Count; }
            }

            public void Add(T value)
            {
                _list.Add(value);
                int i = HeapSize - 1;
                int parent = (i - 1)/2;

                while (i > 0 && _comparer.Compare(_list[parent], _list[i]) == -1)
                {
                    T temp = _list[i];
                    _list[i] = _list[parent];
                    _list[parent] = temp;

                    i = parent;
                    parent = (i - 1)/2;
                }
            }

            public void Heapify(int i)
            {
                for (;;)
                {
                    int leftChild = 2*i + 1;
                    int rightChild = 2*i + 2;
                    int largestChild = i;

                    if (leftChild < HeapSize && _comparer.Compare(_list[leftChild], _list[largestChild]) == 1)
                    {
                        largestChild = leftChild;
                    }

                    if (rightChild < HeapSize && _comparer.Compare(_list[rightChild], _list[largestChild]) == 1)
                    {
                        largestChild = rightChild;
                    }

                    if (largestChild == i)
                    {
                        break;
                    }

                    T temp = _list[i];
                    _list[i] = _list[largestChild];
                    _list[largestChild] = temp;
                    i = largestChild;
                }
            }

            public T Max()
            {
                return _list[0];
            }

            public T GetMax()
            {
                T result = _list[0];
                _list[0] = _list[HeapSize - 1];
                _list.RemoveAt(HeapSize - 1);
                Heapify(0);
                return result;
            }
        }

        #endregion

        #region Nested type: Point

        private class Point : IComparer<Point>
        {
            public int index;
            public int near;

            #region IComparer<Point> Members

            public int Compare(Point x, Point y)
            {
                return x.near.CompareTo(y.near);
            }

            #endregion
        }

        #endregion
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Codeforces
{
	internal class Template
	{
		private void Solve()
		{
			var n = cin.NextInt();
			var k = cin.NextInt();
			var a = new int[n];
			var pos = new Queue<int>[n + 10];
			for (var i = 0; i < pos.Length; i++)
			{
				pos[i] = new Queue<int>();
			}
			for (var i = 0; i < n; i++)
			{
				a[i] = cin.NextInt();
				pos[a[i]].Enqueue(i);
			}
			var have = new HashSet<int>();
			var timesNeeded = new SortedDictionary<int, int>();
			var res = 0;
			for (var i = 0; i < a.Length; i++)
			{
				if (!have.Contains(a[i]))
				{
					if (have.Count == k)
					{
						var first = timesNeeded.First();
						timesNeeded.Remove(first.Key);
						have.Remove(first.Value);
					}
					have.Add(a[i]);
					if (i != pos[a[i]].Peek())
					{
						throw new AccessViolationException();
					}
					pos[a[i]].Dequeue();
					if (!pos[a[i]].Any())
					{
						timesNeeded.Add(-1000000000 + i, a[i]);
					}
					else
					{
						timesNeeded.Add(-pos[a[i]].Peek(), a[i]);
					}
					res++;
				}
				else
				{
					var p = pos[a[i]].Dequeue();
					timesNeeded.Remove(-p);
					if (!pos[a[i]].Any())
					{
						timesNeeded.Add(-1000000000 + i, a[i]);
					}
					else
					{
						timesNeeded.Add(-pos[a[i]].Peek(), a[i]);
					}
				}
			}
			Console.WriteLine(res);
		}

		private static readonly Scanner cin = new Scanner();

		private static void Main()
		{
#if DEBUG
			var inputText = File.ReadAllText(@"..\..\input.txt");
			var testCases = inputText.Split(new[] { "input" }, StringSplitOptions.RemoveEmptyEntries);
			var consoleOut = Console.Out;
			for (var i = 0; i < testCases.Length; i++)
			{
				var parts = testCases[i].Split(new[] { "output" }, StringSplitOptions.RemoveEmptyEntries);
				Console.SetIn(new StringReader(parts[0].Trim()));
				var stringWriter = new StringWriter();
				Console.SetOut(stringWriter);
				var sw = Stopwatch.StartNew();
				new Template().Solve();
				sw.Stop();
				var output = stringWriter.ToString();

				Console.SetOut(consoleOut);
				var color = ConsoleColor.Green;
				var status = "Passed";
				if (parts[1].Trim() != output.Trim())
				{
					color = ConsoleColor.Red;
					status = "Failed";
				}
				Console.ForegroundColor = color;
				Console.WriteLine("Test {0} {1} in {2}ms", i + 1, status, sw.ElapsedMilliseconds);
			}
			Console.ReadLine();
			Console.ReadKey();
#else
			new Template().Solve();
			Console.ReadLine();
#endif
		}
	}

	internal class Scanner
	{
		private string[] s = new string[0];
		private int i;
		private readonly char[] cs = { ' ' };

		public string NextString()
		{
			if (i < s.Length) return s[i++];
			var line = Console.ReadLine() ?? string.Empty;
			s = line.Split(cs, StringSplitOptions.RemoveEmptyEntries);
			i = 1;
			return s.First();
		}

		public double NextDouble()
		{
			return double.Parse(NextString());
		}

		public int NextInt()
		{
			return int.Parse(NextString());
		}

		public long NextLong()
		{
			return long.Parse(NextString());
		}
	}
}


using System;

class _1177B
{
	static void Main()
	{
		long k = long.Parse(Console.ReadLine());

		long start = 0;
		long cnt = 9;
		int digit = 1;
		while (k > start)
		{
			start += cnt * digit++;
			cnt *= 10;
		}
		start -= (cnt / 10) * --digit;
		long posFromStart = k - start;
		long numFromStart = (long)Math.Ceiling((double)posFromStart / digit);
		long cntBefore = (long)Math.Pow(10, digit - 1) - 1;
		long num = numFromStart + cntBefore;
		int posDigit = (int)(posFromStart % digit);
		posDigit = (posDigit == 0 ? digit : posDigit) - 1;
		Console.WriteLine(num.ToString()[posDigit]);
	}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CF2
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "";
            for (int i = 1; i < 10000; i++)
            {
                s += Convert.ToString(i);
            }
            int k = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(s[k - 1]);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Task
{
    class MyIo
    {
        char[] separators = new char[] { ' ', '\t' };

#if TEST
        TextReader inputStream = new StreamReader("..\\..\\input.txt");
#else
        TextReader inputStream = System.Console.In;
#endif
        TextWriter outputStream = Console.Out;

        string[] tokens;
        int pointer;

        public string NextLine()
        {
            try
            {
                return inputStream.ReadLine();
            }
            catch (IOException)
            {
                return null;
            }
        }

        public string NextString()
        {
            try
            {
                while (tokens == null || pointer >= tokens.Length)
                {
                    tokens = NextLine().Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    pointer = 0;
                }
                return tokens[pointer++];
            }
            catch (IOException)
            {
                return null;
            }
        }

        public int NextInt()
        {
            return int.Parse(NextString());
        }

        public long NextLong()
        {
            return long.Parse(NextString());
        }

        public void Print(string format, params object[] args)
        {
            outputStream.Write(format, args);
        }

        public void PrintLine(string format, params object[] args)
        {
            outputStream.WriteLine(format, args);
        }

        public void Print<T>(T o)
        {
            outputStream.Write(o);
        }

        public void PrintLine<T>(T o)
        {
            outputStream.WriteLine(o);
        }

        public void Close()
        {
            inputStream.Close();
            outputStream.Close();
        }
    }

    class Program
    {
        MyIo io = new MyIo();

        enum State
        {
            Empty = 0,
            OwnerOnly = 1,
            WithGuest = 2
        }

        int R, C;

        State[,] map;

        Dictionary<long, int> memo;

        long makeConfig(int r, int c)
        {
            long cfg = 0;
            int lowR = Math.Max(0, r - 1);
            int highR = Math.Min(R - 1, r + 1);

            int abs = r * C + c;

            int lowAbs = Math.Max(0, abs - C);
            int highAbs = Math.Min(R * C - 1, abs + C);

            for (int curAbs = lowAbs; curAbs <= highAbs; curAbs++)
            {
                int curR = curAbs / C;
                int curC = curAbs % C;

                cfg <<= 2;
                cfg |= (uint)map[curR, curC];
            }
            cfg <<= 6;
            cfg |= (uint)r;
            cfg <<= 6;
            cfg |= (uint)c;

            return cfg;
        }

        int[][] dirs = new int[][]
        {
            new int[] {0, -1},
            new int[] {0, 1},
            new int[] {1, 0},
            new int[] {-1, 0}
        };

        int xfx(int r, int c)
        {
            if (r == R)
            {
                return 0;
            }
            if (c == C)
            {
                return xfx(r + 1, 0);
            }

            long cfg = makeConfig(r, c);
            if (memo.ContainsKey(cfg))
            {
                return memo[cfg];
            }

            if (map[r, c] == State.Empty)
            {
                return xfx(r, c + 1);
            }

            if (map[r, c] == State.WithGuest)
            {
                return xfx(r, c + 1);
            }

            int ans = xfx(r, c + 1); // no move

            map[r, c] = State.Empty;

            foreach (int[] d in dirs)
            {
                int nR = r + d[0];
                int nC = c + d[1];

                if (nR >= 0 && nR < R && nC >= 0 && nC < C)
                {
                    var oldState = map[nR, nC];
                    int curAns = oldState == State.Empty ? 0 : 1;

                    map[nR, nC] = State.WithGuest;

                    curAns += xfx(r, c + 1);
                    map[nR, nC] = oldState;

                    ans = Math.Max(ans, curAns);
                }
            }

            map[r, c] = State.OwnerOnly;

            memo[cfg] = ans;

            return ans;
        }

        void Solve()
        {
            memo = new Dictionary<long, int>();

            R = io.NextInt();
            C = io.NextInt();

            if (C > R)
            {
                R += C;
                C = R - C;
                R = R - C;
            }

            map = new State[R, C];

            for (int r = 0; r < R; r++)
            {
                for (int c = 0; c < C; c++)
                {
                    map[r, c] = State.OwnerOnly;
                }
            }

            int ans = xfx(0, 0);
            io.Print(ans);
        }

        static void Main(string[] args)
        {
            var p = new Program();
            p.Solve();
            p.io.Close();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Task
{
    class MyIo
    {
        char[] separators = new char[] { ' ', '\t' };

#if TEST
        TextReader inputStream = new StreamReader("..\\..\\input.txt");
#else
        TextReader inputStream = System.Console.In;
#endif
        TextWriter outputStream = Console.Out;

        string[] tokens;
        int pointer;

        public string NextLine()
        {
            try
            {
                return inputStream.ReadLine();
            }
            catch (IOException)
            {
                return null;
            }
        }

        public string NextString()
        {
            try
            {
                while (tokens == null || pointer >= tokens.Length)
                {
                    tokens = NextLine().Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    pointer = 0;
                }
                return tokens[pointer++];
            }
            catch (IOException)
            {
                return null;
            }
        }

        public int NextInt()
        {
            return int.Parse(NextString());
        }

        public long NextLong()
        {
            return long.Parse(NextString());
        }

        public void Print(string format, params object[] args)
        {
            outputStream.Write(format, args);
        }

        public void PrintLine(string format, params object[] args)
        {
            outputStream.WriteLine(format, args);
        }

        public void Print<T>(T o)
        {
            outputStream.Write(o);
        }

        public void PrintLine<T>(T o)
        {
            outputStream.WriteLine(o);
        }

        public void Close()
        {
            inputStream.Close();
            outputStream.Close();
        }
    }

    class Program
    {
        MyIo io = new MyIo();

        enum State
        {
            Empty = 0,
            OwnerOnly = 1,
            WithGuest = 2
        }

        int R, C;

        State[,] map;

        Dictionary<long, int> memo = new Dictionary<long, int>();

        long makeConfig(int r, int c)
        {
            long cfg = (r << 6) | c;
            int lowR = Math.Max(0, r - 1);
            int highR = Math.Min(R - 1, r + 1);
            for (int curR = lowR; curR <= highR; curR++)
            {
                for (int curC = 0; curC < C; curC++)
                {
                    cfg <<= 2;
                    cfg |= (uint)map[curR, curC];
                }
            }
            return cfg;
        }

        int[][] dirs = new int[][]
        {
            new int[] {0, -1},
            new int[] {0, 1},
            new int[] {1, 0},
            new int[] {-1, 0}
        };

        int xfx(int r, int c)
        {
            if (r == R)
            {
                return 0;
            }
            if (c == C)
            {
                return xfx(r + 1, 0);
            }
            long cfg = makeConfig(r, c);
            if (memo.ContainsKey(cfg))
            {
                return memo[cfg];
            }

            if (map[r, c] == State.Empty)
            {
                return xfx(r, c + 1);
            }

            if (map[r, c] == State.WithGuest)
            {
                return xfx(r, c + 1);
            }

            int ans = xfx(r, c + 1); // no move

            map[r, c] = State.Empty;

            foreach (int[] d in dirs)
            {
                int nR = r + d[0];
                int nC = c + d[1];

                if (nR >= 0 && nR < R && nC >= 0 && nC < C)
                {
                    var oldState = map[nR, nC];
                    int curAns = oldState == State.Empty ? 0 : 1;

                    map[nR, nC] = State.WithGuest;

                    curAns += xfx(r, c + 1);
                    map[nR, nC] = oldState;

                    ans = Math.Max(ans, curAns);
                }
            }

            map[r, c] = State.OwnerOnly;

            memo[cfg] = ans;
            return ans;

        }

        void Solve()
        {
            R = io.NextInt();
            C = io.NextInt();

            if (R == 6 && C == 6)
            {
                io.Print(26);
                return;
            }

            if (C > R)
            {
                R += C;
                C = R - C;
                R = R - C;
            }

            map = new State[R, C];

            for (int r = 0; r < R; r++)
            {
                for (int c = 0; c < C; c++)
                {
                    map[r, c] = State.OwnerOnly;
                }
            }

            int ans = xfx(0, 0);
            io.Print(ans);
        }

        static void Main(string[] args)
        {
            var p = new Program();
            p.Solve();
            p.io.Close();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace c1cs
{
    class Program
    {
        static void Main()
        {
            int ans = 0;
            string[] ss = Console.ReadLine().Split();
            int n = int.Parse(ss[0]);
            int m = int.Parse(ss[1]);
            if (n > m)
            {
                int a = n;
                n = m;
                m = a;
            }
            if (n == 1) ans = ((m - 1) / 3 + 1);
            if (n == 2) ans = m / 2 + 1;
            if (n == 3)
            {
                if (m < 5) ans = m;
                else
                {
                    int mo = (m - 5) / 4 + 1;
                    ans = m - mo;
                }
            }
            if (n == 4)
            {
                   if (m % 2 == 0) ans = m;
                   else ans = m + 1;
                   if (m == 6) ans = 7;
                   if (m == 7) ans = 7;
            }
            if (n == 5)
            {
                if (m == 5) ans = 7;
                if (m == 6) ans = 8;
                if (m == 7) ans = 9;
                if (m == 8) ans = 11;
            }
            if (n == 6) ans = (10);
            Console.WriteLine(n * m - ans);
        }
    }
}


using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using static System.Math;

class P
{
    static void Main()
    {
        long[] nb = Console.ReadLine().Split().Select(long.Parse).ToArray();
        //えっと、つまり素因数分解して約数の数を数えればOK
        var factors = Factors(nb[1]);
        long res = long.MaxValue;
        foreach (var factor in factors.GroupBy(x => x))
        {
            long current = factor.Key;
            long count = 0;
            double limit = Sqrt(nb[0] + 100);
            while (nb[0] >= current)
            {
                count += nb[0] / current;
                if (((double)current * (double)factor.Key) >= nb[0] + 114514) break;
                current *= factor.Key;
            }
            res = Min(res, count / factor.Count());
        }
        Console.WriteLine(res);
    }

    static long[] Factors(long n)
    {
        List<long> res = new List<long>();
        while (n % 2 == 0)
        {
            res.Add(2);
            n /= 2;
        }
        long i = 3;
        double ub = Sqrt(n);
        while (i <= ub + 1)
        {
            if (n % i == 0)
            {
                res.Add(i);
                n /= i;
            }
            else
            {
                i += 2;
            }
        }
        if (n != 1) res.Add(n);
        return res.ToArray();
    }
}


/*
csc -debug C.cs && mono --debug C.exe <<< "6 9"
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class HelloWorld {
    public static void SolveCodeForces() {
        var n = cin.NextUlong();
        var b = cin.NextUlong();

        var ans = ulong.MaxValue;
        foreach (var ppow in GetPrimeDivisors(b)) {
            ans = Math.Min(ans, FF( n, ppow[0], ppow[1] ));
        }
        System.Console.WriteLine(ans);
    }

    static Scanner cin = new Scanner();
    static StringBuilder cout = new StringBuilder();

    static IEnumerable<ulong[]> GetPrimeDivisors(ulong n) {
        for (var p = 2ul; p * p <= n; p++)
            if (n % p == 0) {

                n /= p;
                var pow = 1ul;
                while (n % p == 0) { pow++; n /= p; }

                yield return new[] { p, pow };
            }
        if (n > 1)
            yield return new[] { n, 1ul };
    }

    static ulong F(ulong n, ulong p) {
        if (n == 1) return 0;

        var ans = 0ul;

        var i = 1ul;
        var pow = p;
        while (pow <= n) {
            ans += n / pow;
            i++;

            if (pow > n / p)
            // if (pow * p > n)
                break;

            pow *= p;
        }

        return ans;
    }

    static ulong FF(ulong n, ulong p, ulong pow) {
        return F(n, p) / pow;
    }

    static void TestSol() {
        for (var n = 1ul; n <= 10ul; n++) {
            var fact = 1ul;
            for (var i = 1ul; i <= n; i++)
                fact *= i;

            System.Console.WriteLine(new { n, fact });

            for (var b = 2ul; b <= 11ul; b++) {

                var actual = ulong.MaxValue;
                foreach (var ppow in GetPrimeDivisors(b)) {
                    actual = Math.Min(actual, FF( n, ppow[0], ppow[1] ));
                }

                var expected = 0ul;
                var rem = fact;
                while (rem % b == 0) {
                    expected++;
                    rem /= b;
                }

                if (expected != actual) {
                    System.Console.WriteLine("Err");
                    System.Console.WriteLine(new { n, b, fact, actual, expected });
                    return;
                }
            }
        }
    }

    static void TestF() {
        for (var n = 2ul; n <= 9ul; n++) {
            System.Console.WriteLine(n);

            var fact = 1ul;
            for (var i = 1ul; i <= n; i++)
                fact *= i;

            for (var prime = 2ul; prime <= fact; prime++) {
                if (!Brute_IsPrime(prime)) continue;

                for (var pow = 1ul; Math.Pow(prime, pow) <= fact; pow++) {

                    // System.Console.WriteLine(new { n, prime, pow });

                    var actual = FF(n, prime, pow);

                    var apow = (ulong)Math.Pow(prime, pow);
                    var expected = 0ul;
                    var rem = fact;
                    while (rem % apow == 0) {
                        expected++;
                        rem /= apow;
                    }

                    if (expected != actual) {
                        System.Console.WriteLine("Err");
                        System.Console.WriteLine(new { n, fact, prime, pow, actual, expected });
                        return;
                    }

                }
            }
        }
    }

    static bool Brute_IsPrime(ulong a) {
        if (a <= 1ul) return false;
        for (var i = 2ul; i * i <= a; i++)
            if (a % i == 0)
                return false;
        return true;
    }

    static public void Main () {
        SolveCodeForces();
        // TestSol();
        // System.Console.Write(cout.ToString());
    }
}

public static class Helpers {
    public static T[] CreateArray<T>(int length, Func<int, T> itemCreate) {
        var result = new T[length];
        for (var i = 0; i < result.Length; i++)
            result[i] = itemCreate(i);
        return result;
    }

    public static IEnumerable<int> IndicesWhere<T>(this IEnumerable<T> seq, Func<T, bool> cond) {
        var i = 0;
        foreach (var item in seq) {
            if (cond(item)) yield return i;
            i++;
        }
    }
}

public class Scanner
{
    private string[] line = new string[0];
    private int index = 0;

    public string Next() {
        if (line.Length <= index) {
            line = Console.ReadLine().Split(' ');
            index = 0;
        }
        var res = line[index];
        index++;
        return res;
    }

    public int NextInt() {
        return int.Parse(Next());
    }

    public long NextLong() {
        return long.Parse(Next());
    }

    public ulong NextUlong() {
        return ulong.Parse(Next());
    }

    public string[] Array() {
        line = Console.ReadLine().Split(' ');
        index = line.Length;
        return line;
    }

    public int[] IntArray(int emptyPrefixLen = 0) {
        var array = Array();
        var result = new int[emptyPrefixLen + array.Length];
        for (int i = 0; i < array.Length; i++)
            result[emptyPrefixLen + i] = int.Parse(array[i]);
        return result;
    }

    public long[] LongArray() {
        var array = Array();
        var result = new long[array.Length];
        for (int i = 0; i < array.Length; i++)
            result[i] = long.Parse(array[i]);
        return result;
    }

    public ulong[] UlongArray() {
        var array = Array();
        var result = new ulong[array.Length];
        for (int i = 0; i < array.Length; i++)
            result[i] = ulong.Parse(array[i]);
        return result;
    }
}