//

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

namespace sar_cs
{
    static class Helpers
    {
        public static string Join<T>(this IEnumerable<T> objs, string sep)
        {
            var sb = new StringBuilder();
            foreach (var s in objs) { if (sb.Length != 0) sb.Append(sep); sb.Append(s); }
            return sb.ToString();
        }

        public static string AsString(this double a, int digits)
        {
            return a.ToString("F" + digits, CultureInfo.InvariantCulture);
        }

        public static T[] Copy<T>(this T[] a)
        {
            var b = new T[a.Length]; a.CopyTo(b, 0); return b;
        }

        public static T[][] Copy<T>(this T[][] a)
        {
            return a.Select(z => z.Copy()).ToArray();
        }

        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection)
        {
            if (collection.Take(11).Count() <= 10) return collection;
            var a = collection is T[] ? (T[])collection : collection.ToArray();
            int N = a.Length;
            for (int i = 0, p1 = 0, p2 = 1; i < N / 2; i++)
            {
                p1 += 3; if (p1 >= N) p1 -= N;
                p2 -= 7; if (p2 < 0) p2 += N;
                T t = a[p1]; a[p1] = a[p2]; a[p2] = t;
            }
            return a;
        }

        public static string AsString<T>(this T[,] a, string separator)
        {
            var sb = new StringBuilder();
            int n0 = a.GetLength(0);
            int n1 = a.GetLength(1);
            for (int r = 0; r < n0; r++)
            {
                for (int c = 0; c < n1; c++)
                {
                    if (c != 0) sb.Append(separator); sb.Append(a[r, c]);
                }
                sb.AppendLine();
            }
            //sb.AppendLine();
            return sb.ToString();
        }

        public static Stopwatch SW = Stopwatch.StartNew();
    }

    public class Program
    {
        #region Helpers

        public class Parser
        {
            const int BufSize = 8000;
            TextReader s;
            char[] buf = new char[BufSize];
            int bufPos;
            int bufDataSize;
            bool eos;   // eos read to buffer
            int lastChar = -2;
            int nextChar = -2;
            StringBuilder sb = new StringBuilder();

            void FillBuf()
            {
                if (eos) return;
                bufDataSize = s.Read(buf, 0, BufSize);
                if (bufDataSize == 0) eos = true;
                bufPos = 0;
            }

            int Read()
            {
                if (nextChar != -2)
                {
                    lastChar = nextChar;
                    nextChar = -2;
                }
                else
                {
                    if (bufPos == bufDataSize) FillBuf();
                    if (eos) lastChar = -1; else lastChar = buf[bufPos++];
                }
                return lastChar;
            }

            void Back()
            {
                if (lastChar == -2) throw new Exception();  // no chars were ever read
                nextChar = lastChar;
            }

            public Parser()
            {
                s = Console.In;
            }

            public int ReadInt()
            {
                int res = 0;
                int sign = -1;
                int c;
                do { c = Read(); } while (c >= 0 && char.IsWhiteSpace((char)c));
                if (c == '-') { sign = 1; c = Read(); }
                int len = 0;
                while (c >= 0 && !char.IsWhiteSpace((char)c))
                {
                    if ((uint)(c -= 48) >= 10) throw new FormatException();
                    len++;
                    res = checked(res * 10 - c);
                    c = Read();
                }
                if (len == 0) throw new FormatException();
                Back();
                return checked(res * sign);
            }

            public long ReadLong()
            {
                long res = 0;
                int sign = -1;
                int c;
                do { c = Read(); } while (c >= 0 && char.IsWhiteSpace((char)c));
                if (c == '-') { sign = 1; c = Read(); }
                int len = 0;
                while (c >= 0 && !char.IsWhiteSpace((char)c))
                {
                    if ((uint)(c -= 48) >= 10) throw new FormatException();
                    len++;
                    res = checked(res * 10 - c);
                    c = Read();
                }
                if (len == 0) throw new FormatException();
                Back();
                return checked(res * sign);
            }

            public int ReadLnInt()
            {
                int res = ReadInt(); ReadLine(); return res;
            }

            public long ReadLnLong()
            {
                long res = ReadLong(); ReadLine(); return res;
            }

            public double ReadDouble()
            {
                int c;
                do { c = Read(); } while (c >= 0 && char.IsWhiteSpace((char)c));

                int sign = 1;
                if (c == '-') { sign = -1; c = Read(); }

                sb.Length = 0;
                while (c >= 0 && !char.IsWhiteSpace((char)c))
                {
                    sb.Append((char)c); c = Read();
                }

                Back();
                var res = double.Parse(sb.ToString(), CultureInfo.InvariantCulture);
                return res * sign;
            }

            public string ReadLine()
            {
                int c = Read();
                sb.Length = 0;
                while (c != -1 && c != 13 && c != 10)
                {
                    sb.Append((char)c); c = Read();
                }
                if (c == 13) { c = Read(); if (c != 10) Back(); }
                return sb.ToString();
            }

            public bool SeekEOF
            {
                get
                {
                L0:
                    int c = Read();
                    if (c == -1) return true;
                    if (char.IsWhiteSpace((char)c)) goto L0;
                    Back();
                    return false;
                }
            }

            public int[] ReadIntArr(int n)
            {
                var a = new int[n]; for (int i = 0; i < n; i++) a[i] = ReadInt(); return a;
            }

            public long[] ReadLongArr(int n)
            {
                var a = new long[n]; for (int i = 0; i < n; i++) a[i] = ReadLong(); return a;
            }
        }

        class Writer
        {
            const int BufSize = 32000;
            char[] buf = new char[BufSize];
            int bufPos = 0;
            TextWriter output = Console.Out;
            Stack<char> st = new Stack<char>();

            public void Flush()
            {
                output.Write(buf, 0, bufPos); bufPos = 0;
                output.Flush();
            }

            void BufSpaceNeeded(int n)
            {
                if (n > BufSize) throw new ArgumentOutOfRangeException("n");
                if (bufPos + n > BufSize) { output.Write(buf, 0, bufPos); bufPos = 0; }
            }

            public void Write(char a)
            {
                BufSpaceNeeded(1);
                buf[bufPos++] = a;
            }

            public void Write(string s)
            {
                int l = s.Length;
                for (int x = 0; x < l; )
                {
                    int t = Math.Min(l - x, BufSize - bufPos);
                    s.CopyTo(x, buf, bufPos, t); bufPos += t; x += t;
                    if (x < l) BufSpaceNeeded(1);   // force flush
                }
            }

            public void WriteLine()
            {
                BufSpaceNeeded(2);
                buf[bufPos++] = '\r'; buf[bufPos++] = '\n';
            }

            public void Write(object o) { Write(o.ToString()); }

            public void Write(uint a)
            {
                BufSpaceNeeded(10);
                do { st.Push((char)(a % 10 + 48)); a /= 10; } while (a != 0);
                while (st.Count != 0) buf[bufPos++] = st.Pop();
            }

            public void Write(ulong a)
            {
                BufSpaceNeeded(20);
                do { st.Push((char)(a % 10 + 48)); a /= 10; } while (a != 0);
                while (st.Count != 0) buf[bufPos++] = st.Pop();
            }

            public void Write(int a)
            {
                BufSpaceNeeded(11);
                if (a < 0) { buf[bufPos++] = '-'; a = -a; }
                Write((uint)a);
            }

            public void Write(long a)
            {
                BufSpaceNeeded(21);
                if (a < 0) { buf[bufPos++] = '-'; a = -a; }
                Write((ulong)a);
            }

            public void Write(double a, int digits)
            {
                Write(a.AsString(digits));
            }

            public void WriteLine(int a) { Write(a); WriteLine(); }
            public void WriteLine(long a) { Write(a); WriteLine(); }
            public void WriteLine(uint a) { Write(a); WriteLine(); }
            public void WriteLine(ulong a) { Write(a); WriteLine(); }
            public void WriteLine(string s) { Write(s); WriteLine(); }
            public void WriteLine(object o) { Write(o); WriteLine(); }
        }

        static void pe() { Console.WriteLine("???"); Environment.Exit(0); }
        static void re() { throw new Exception(); }
        static void Swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; }
        static int Sqr(int a) { return a * a; }
        static long SqrL(int a) { return (long)a * a; }
        static long Sqr(long a) { return a * a; }
        static double Sqr(double a) { return a * a; }
        static double Sqrt(double a) { return Math.Sqrt(a); }

        static StringBuilder sb = new StringBuilder();
        static Random rnd = new Random(5);

        #endregion Helpers

        const uint M = 1000000007;
        static uint[,] PROD = new uint[16, 16];

        static int h, w, k;
        static int wh1;
        static int predefined_colors;
        static int[] vertMasks;
        static uint result;
        static int[,] resultmap = new int[16, 16];

        static int[,] map;
        static int[] color_mapping_to, color_mapping_from;

        static uint DistinctMappingsCount(int from_count, int to_count)
        {
            if (from_count > to_count) throw new Exception();
            if (from_count < 0) throw new Exception();
            return /*k! / (k-max)! */ PROD[to_count - from_count + 1, to_count];
        }

        static void Per2(int y, int x, int vertmask)
        {
            if (y >= h)
            {
                var qwe = resultmap;

                uint t = 1;
                result += t;

                if (result >= M) result -= M;
                return;
            }

            int used = vertmask | vertMasks[x];
            for (int i = 1; i <= k; i++)
                if ((used >> i & 1) == 0)
                {
                    int mc = map[y, x];
                    if (mc != 0)
                    {
                        if (i != mc) continue;
                    }

                    vertMasks[x] |= (1 << i);
                    resultmap[y, x] = i;
                    if (x == w - 1) Per2(y + 1, 0, 0);
                    else Per2(y, x + 1, used | (1 << i));
                    resultmap[y, x] = 0;
                    vertMasks[x] &= ~(1 << i);
                }
        }

        static void Per(int y, int x, int max, int vertmask)
        {
            var qwe = resultmap;

            if (y >= h)
            {
                if (max < wh1) throw new Exception();
                if (max > k) throw new Exception();
                // wh1 <= max <= k

                //result += DistinctMappingsCount(max, k);

                if (k < predefined_colors) throw new Exception();
                if (max < predefined_colors) throw new Exception();
                uint t = DistinctMappingsCount(max - predefined_colors, k - predefined_colors);
                result += t;

                if (result >= M) result -= M;
                return;
            }

            int used = vertmask | vertMasks[x];
            for (int i = 1; i <= max + 1; i++)
                if (i <= k)
                    if ((used >> i & 1) == 0)
                    {
                        int mc = map[y, x];
                        bool mapping = false;

                        if (mc != 0)
                        {
                            if (color_mapping_from[mc] == 0 && color_mapping_to[i] == 0)
                            {
                                mapping = true;
                                color_mapping_from[mc] = i;
                                color_mapping_to[i] = mc;
                            }
                            else if (color_mapping_from[mc] == 0 && color_mapping_to[i] != 0)
                            {
                                continue; // color i already mapped to other color
                            }
                            else if (color_mapping_from[mc] != 0 && color_mapping_to[i] == 0)
                            {
                                continue; // color mc already mapped from other color
                            }
                            else if (color_mapping_from[mc] != 0 && color_mapping_to[i] != 0)
                            {
                            }
                        }

                        vertMasks[x] |= (1 << i);
                        resultmap[y, x] = i;
                        if (x == w - 1) Per(y + 1, 0, Math.Max(i, max), 0);
                        else Per(y, x + 1, Math.Max(i, max), used | (1 << i));
                        resultmap[y, x] = 0;
                        vertMasks[x] &= ~(1 << i);

                        if (mapping)
                        {
                            color_mapping_to[i] = 0;
                            color_mapping_from[mc] = 0;
                        }

                    }
        }

        static void Main()
        {
            checked
            {
#if !ONLINE_JUDGE
                Console.SetIn(File.OpenText("_input"));
#endif
                //Console.SetOut(File.CreateText("_output"));
                var parser = new Parser();
                var o = new Writer();
                try
                {
                    for (uint i = 0; i < 16; i++)
                        for (uint j = 0; j < 16; j++)
                        {
                            if (j + 1 < i) PROD[i, j] = 0;
                            else if (j < i) PROD[i, j] = 1;
                            else if (j == i) PROD[i, j] = i;
                            else PROD[i, j] = (uint)(PROD[i, j - 1] * (ulong)j % M);
                        }

                    while (!parser.SeekEOF)
                    {
                        h = parser.ReadInt();
                        w = parser.ReadInt();
                        k = parser.ReadInt();
                        wh1 = w + h - 1;

                        map = new int[16, 16];

                        for (int y = 0; y < h; y++)
                            for (int x = 0; x < w; x++)
                                if (y < 16 && x < 16) map[y, x] = parser.ReadInt();
                                else parser.ReadInt();

                        //var mapping = new int[16];
                        //for (int y = 0; y < h; y++)
                        //    for (int x = 0; x < w; x++)
                        //    {
                        //        for (int color = 1; ; color++)
                        //        {
                        //            for (int y = 0; y < h; y++)
                        //                for (int x = 0; x < w; x++) { }
                        //        }
                        //    }

                        result = 0;
                        if (wh1 > k)
                        {
                        }
                        else
                        {
                            predefined_colors = map.Cast<int>().Where(c => c != 0).Distinct().Count();
                            color_mapping_from = new int[16];
                            color_mapping_to = new int[16];
                            vertMasks = new int[16];
                            Per(0, 0, 0, 0);
                            //o.WriteLine(result); result = 0;

                            //color_mapping_from = new int[16];
                            //color_mapping_to = new int[16];
                            //vertMasks = new int[16];
                            //Per2(0, 0, 0);
                        }

                        o.WriteLine(result);
                    }
                }
                finally
                {
                    o.Flush();
                }
            }
        }

        //static void Main()
        //{
        //    new Thread(Main2, 50 << 20).Start();
        //}
    }
}


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

namespace ConsoleApp2
{
    class Program
    {
        static long NOD(long a, long b)
        {
            if (b == 0)
                return a;
            return NOD(b, a % b);
        }
        static void Main(string[] args)
        {
            long X = long.Parse(Console.ReadLine());
            long min = X;
            for(int i = 2; (long)i*i <= X; i++)
            {
                if (X % i == 0)
                {
                    long a = i;
                    long b = X / a;
                    if (NOD(a, b) == 1)
                    {
                        min = b;
                    }
                }
                if (i == 1000000)
                    Console.WriteLine(1);
            }
            Console.WriteLine($"{X/min} {min}");
        }
    }
}


using System;
using System.Collections.Generic;

namespace Day_23
{
    class Program
    {
        static Int64 gcd(Int64 a, Int64 b)
        {
            if (a == 0)
                return b;
            return gcd(b % a, a);
        }
        static Int64 lcm(Int64 a, Int64 b)
        {
            return (a * b) / gcd(a, b);
        }
        static void Main(string[] args)
        {
            Int64 X = Convert.ToInt64(Console.ReadLine());
            if (X == 1)
            {
                Console.WriteLine("1 1");
                return;
            }
            SortedDictionary<Int64, Int64> keyValuePairs = new SortedDictionary<Int64, Int64>();
            Int64 last_added = 1;

            List<int> banned_primes = new List<int>();
            if (X % 2 != 0) banned_primes.Add(2);
            if (X % 3 != 0) banned_primes.Add(3);
            if (X % 5 != 0) banned_primes.Add(5);
            if (X % 7 != 0) banned_primes.Add(7);

            keyValuePairs.Add(1, X);
            for (Int64 i = 2; i < 10; i++)
            {
                bool found = false;
                foreach (int ix in banned_primes)
                {
                    if (i % ix == 0)
                    {
                        found = true;
                        break;
                    }
                }
                if (found) continue;

                while (i <= X)
                {
                    if (X % i == 0)
                    {
                        if (keyValuePairs.ContainsKey(i) || keyValuePairs.ContainsKey(X / i))
                        {
                            i += i;
                            continue;
                        }
                        else
                        {
                            if (lcm(i, X / i) == X)
                            {
                                keyValuePairs.Add(i, X / i);
                                last_added = i;
                            }
                        }
                    }
                    i += i;
                }
            }
            Console.WriteLine($"{last_added} {keyValuePairs[last_added]}");
        }
    }
}


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

namespace ConsoleApp2
{
    class Program
    {
        static long NOD(long a, long b)
        {
            if (b == 0)
                return a;
            return NOD(b, a % b);
        }
        static void Main(string[] args)
        {
            long X = long.Parse(Console.ReadLine());
            long min = X;
            for(int i = 2; (long)i*i <= X; i++)
            {
                if (X % i == 0)
                {
                    long a = i;
                    long b = X / a;
                    if (NOD(a, b) == 1)
                    {
                        min = b;
                    }
                }
            }
            Console.WriteLine($"{X/min} {min}");
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace Zadanie_1
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger ansa = new BigInteger(1e18);
            BigInteger ansb = new BigInteger(1e18);
            BigInteger[] mass = new BigInteger[0];//Вектор, но только не вектор, а лишь жалкая копия
            int X = Convert.ToInt32(Console.ReadLine());
            for(int i = 2; i * i <= X; i++)
            {
                if (X % i == 0)
                {
                    BigInteger cur = new BigInteger(1);
                    while (X % i == 0)
                    {
                        X /= i;
                        cur *= i;
                    }
                    Array.Resize<BigInteger>(ref mass, mass.Length + 1);
                    mass[mass.Length - 1] = cur;
                }
            }
            if(X > 1)
            {
                Array.Resize<BigInteger>(ref mass, mass.Length + 1);
                mass[mass.Length - 1] = X;
            }
            for(int i = 0; i < (1 << mass.Length); i++)
            {
                BigInteger a = new BigInteger(1);
                BigInteger b = new BigInteger(1);
                for(int j = 0; j < mass.Length; j++)
                {
                    if (((i >> j) & 1)>0) a *= mass[j];
                    else b *= mass[j];
                }
                if (Math.Max((double)a, (double)b) < Math.Max((double)ansa, (double)ansb))
                {
                    ansa = a;
                    ansb = b;
                }
            }
            Console.WriteLine(ansa + " " + ansb);
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace Zadanie_1
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger ansa = new BigInteger(1e18);
            BigInteger ansb = new BigInteger(1e18);
            BigInteger[] mass = new BigInteger[0];//Вектор, но только не вектор, а лишь жалкая копия
            int X = Convert.ToInt32(Console.ReadLine());
            for(int i = 2; i * i <= X; i++)
            {
                if (X % i == 0)
                {
                    BigInteger cur = new BigInteger(1);
                    while (X % i == 0)
                    {
                        X /= i;
                        cur *= i;
                    }
                    Array.Resize<BigInteger>(ref mass, mass.Length + 1);
                    mass[mass.Length - 1] = cur;
                }
            }
            if(X > 1)
            {
                Array.Resize<BigInteger>(ref mass, mass.Length + 1);
                mass[mass.Length - 1] = X;
            }
            for(int i = 0; i < (1 << mass.Length); i++)
            {
                BigInteger a = new BigInteger(1);
                BigInteger b = new BigInteger(1);
                for(int j = 0; j < mass.Length; j++)
                {
                    if (((i >> j) & 1)>0) a *= mass[j];
                    else b *= mass[j];
                }
                if (Math.Max((double)a, (double)b) < Math.Max((double)ansa, (double)ansb))
                {
                    ansa = a;
                    ansb = b;
                }
            }
            Console.WriteLine(ansa + " " + ansb);
            Console.ReadKey();
        }
    }
}


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

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            double ansa = 1e18;
            double ansb = 1e18;
            double[] mass = new double[0];
            double X = Convert.ToDouble(Console.ReadLine());
            for (long i = 2; i * i <= X; i++)
            {
                if (X % i == 0)
                {
                    double cur = 1;
                    while (X % i == 0)
                    {
                        X /= i;
                        cur *= i;
                    }
                    Array.Resize<double>(ref mass, mass.Length + 1);
                    mass[mass.Length - 1] = cur;
                }
                //Console.WriteLine("Ya rabotau" + DateTime.Now);
            }
            if (X > 1)
            {
                Array.Resize<double>(ref mass, mass.Length + 1);
                mass[mass.Length - 1] = X;
            }
            for (int i = 0; i < (1 * Math.Pow(2, mass.Length); i++)
            {
                double a = 1;
                double b = 1;
                for (int j = 0; j < mass.Length; j++)
                {
                    if (((i >> j) & 1) > 0) a *= mass[j];
                    else b *= mass[j];
                }
                if (Math.Max(a, b) < Math.Max(ansa, ansb))
                {
                    ansa = a;
                    ansb = b;
                }
            }
            Console.WriteLine(ansa + " " + ansb);
            //Console.ReadKey();
        }
    }
}


using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using StringBuilder = System.Text.StringBuilder;
using System.Numerics;

namespace Program
{

    public class Solver
    {
        public void Solve()
        {
            var w = sc.Long();
            var m = sc.Long();

            if (w <= 3 || m == 1 || ok(m, w))
                IO.Printer.Out.WriteLine("YES");
            else IO.Printer.Out.WriteLine("NO");

        }
        public bool ok(long m, long w)
        {
            if (m == 0) return true;
            long sum = 0;
            for (long i = 1; true; i *= w)
            {
                var min = i - sum;
                var max = i + sum;
                if (m < min) return false;
                else if (min <= m && m <= max)
                    return ok(Math.Abs(m - i), w);
                sum += i;

            }
        }

        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 < n; ++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(System.Linq.Enumerable.ToArray(ie)); }
    static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); }
    static public void Main()
    {
        var solver = new Program.Solver();
        solver.Solve();
        Program.IO.Printer.Out.Flush();
    }
}
#endregion
#region Ex
namespace Program.IO
{
    using System.IO;
    using System.Text;
    using System.Globalization;
    public class Printer : StreamWriter
    {
        static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; }
        public static Printer Out { get; set; }
        public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
        public Printer(System.IO.Stream stream) : base(stream, new UTF8Encoding(false, true)) { }
        public Printer(System.IO.Stream stream, Encoding encoding) : base(stream, encoding) { }
        public void Write<T>(string format, T[] source) { base.Write(format, source.OfType<object>().ToArray()); }
        public void WriteLine<T>(string format, T[] source) { base.WriteLine(format, source.OfType<object>().ToArray()); }
    }
    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 = (char)read())
                if (b == 0) break;
                else if (b != '\r') sb.Append(b);
            return sb.ToString();
        }
        public long Long()
        {
            if (isEof) return long.MinValue;
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        public int Integer() { return (isEof) ? int.MinValue : (int)Long(); }
        public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
        private T[] enumerate<T>(int n, Func<T> f)
        {
            var a = new T[n];
            for (int i = 0; i < n; ++i) a[i] = f();
            return a;
        }

        public char[] Char(int n) { return enumerate(n, Char); }
        public string[] Scan(int n) { return enumerate(n, Scan); }
        public double[] Double(int n) { return enumerate(n, Double); }
        public int[] Integer(int n) { return enumerate(n, Integer); }
        public long[] Long(int n) { return enumerate(n, Long); }
    }
}
#endregion


using System;

namespace TaskC
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split(' ', '\t');
            int w = Convert.ToInt32(s[0]);
            int m = Convert.ToInt32(s[1]);

            Console.WriteLine(Check(w, m) ? "YES" : "NO");
        }

        private static bool Check(int w, int m, bool first = true)
        {
            if (m == 0)
                return true;
            if (m % w == 0)
                return Check(w, m / w);
            return first && (Check(w, m - 1, false) || Check(w, m + 1, false));
        }
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace _308c
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var w = d[0];
            var m = d[1];
            var val = new int[101];
            var i = 1;
            while (true)
            {
                if (m == 0)
                {
                    break;
                }

                var rem = m % w;
                val[i] = rem;
                i++;
                m /= w;
            }

            var av = new bool[101];
            for (int j = 1; j < 101; j++)
            {
                av[j] = true;
            }

            for (int j = 1; j < 101; j++)
            {
                if (val[j] == 0 || val[j] == 1)
                {
                    continue;
                }

                if (val[j] < w - 2)
                {
                    Console.WriteLine("NO");
                    return;
                }

                if (val[j] == w - 2)
                {
                    if (j == 100)
                    {
                        Console.WriteLine("NO");
                        return;
                    }

                    if (!av[j - 1])
                    {
                        Console.WriteLine("NO");
                        return;
                    }

                    av[j - 1] = false;
                    av[j] = false;
                    val[j + 1]++;
                }

                if (val[j] == w - 1)
                {
                    if (j == 100)
                    {
                        Console.WriteLine("NO");
                        return;
                    }

                    av[j] = false;
                    val[j + 1]++;
                }
            }

            Console.WriteLine("YES");

            //for (int j = 1; j < 101; j++)
            //{

            //}

            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


using System;

namespace Lara_Croft_and_the_New_Game
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split();
            ulong n = ulong.Parse(input[0]);
            ulong m = ulong.Parse(input[1]);
            ulong k = ulong.Parse(input[2]);
            ulong X = 0, Y = 0;

            if (k < n) { X = k + 1; Y = 1; }
            else if (k >= n && k <= m + n - 2) { X = n; Y = k - n + 2; }
            else
            {
                k -= n + m - 1;
                ulong temp = k / (m - 1);
                X = (n - 1) - temp;
                bool isEven = X % 2 == 0;
                ulong remains = k % (m - 1);
                if (!isEven) Y = m - remains;
                else Y = remains + 2;
            }
            Console.WriteLine("{0} {1}", X, Y);

        }
    }
}


using System;

namespace CSharp
{
    class _976B
    {
        public static void Main()
        {
            var tokens = Console.ReadLine().Split();

            long n = long.Parse(tokens[0]);
            long m = long.Parse(tokens[1]);
            long k = long.Parse(tokens[2]);

            if (k < n)
            {
                Console.WriteLine($"{1 + k} 1");
            }
            else
            {
                k -= n;
                m--;

                long row = n - k / m;
                long column = (n - row) % 2 == 0 ? 2 + k % m : m + 1 - k % m;

                Console.WriteLine($"{row} {column}");
            }
        }
    }
}


#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using static System.Array;
using static System.Math;

// ReSharper disable InconsistentNaming
#pragma warning disable CS0675
#endregion

partial class Solution
{
	#region Variables
	const int MOD = 1000000007;
	const int FactCache = 1000;
	const long BIG = long.MaxValue >> 15;

	#endregion

	public void Solve()
	{
		int n = Ni();
		int k = Ni();

		var y = new List<long>();
		long sum = 0;
		y.Add(sum);
		for (int i = 0; i <= k; i++)
		{
			sum = (sum + ModPow(i + 1, k));
			if (sum >= MOD) sum -= MOD;
			y.Add(sum);
		}

		if (n < y.Count)
			WriteLine(y[n]);
		else
			WriteLine(Lagrange(y, n));
	}

	long Lagrange(List<long> y, long x)
	{
		long ans = 0;
		long k = 1;
		for (int j = 1; j < y.Count; j++)
		{
			k = (k * (x - j)) % MOD;
			k = MOD - Div(k, j);
		}

		for (int i = 0; i < y.Count; i++)
		{
			ans = (ans + y[i] * k) % MOD;
			if (i + 1 >= y.Count) break;
			k = k * Div(x - i, x - (i + 1)) % MOD * Div(i - y.Count + 1, i + 1) % MOD;
		}

		return Fix(ans);
	}

	#region Library
	#region Mod Math

	static int[] _inverse;
	static long Inverse(long n)
	{
		long result;

		if (_inverse == null)
			_inverse = new int[1000];

		if (n >= 0 && n < _inverse.Length && (result = _inverse[n]) != 0)
			return result - 1;

		result = InverseDirect((int)n);
		if (n >= 0 && n < _inverse.Length)
			_inverse[n] = (int)(result + 1);
		return result;
	}

	public static int InverseDirect(int a)
	{
		if (a < 0) return -InverseDirect(-a);
		int t = 0, r = MOD, t2 = 1, r2 = a;
		while (r2 != 0)
		{
			var q = r / r2;
			t -= q * t2;
			r -= q * r2;

			if (r != 0)
			{
				q = r2 / r;
				t2 -= q * t;
				r2 -= q * r;
			}
			else
			{
				r = r2;
				t = t2;
				break;
			}
		}
		return r <= 1 ? (t >= 0 ? t : t + MOD) : -1;
	}

	static long Mult(long left, long right) =>
		(left * right) % MOD;

	static long Div(long left, long divisor) =>
		left * Inverse(divisor) % MOD;

	static long Add(long x, long y) =>
		(x += y) >= MOD ? x - MOD : x;

	static long Subtract(long x, long y) => (x -= y) < 0 ? x + MOD : x;

	static long Fix(long n) => (n %= MOD) >= 0 ? n : n + MOD;

	static long ModPow(long n, long p, long mod = MOD)
	{
		long b = n;
		long result = 1;
		while (p != 0)
		{
			if ((p & 1) != 0)
				result = (result * b) % mod;
			p >>= 1;
			b = (b * b) % mod;
		}
		return result;
	}

	static List<long> _fact;

	static long Fact(int n)
	{
		if (_fact == null) _fact = new List<long>(FactCache) { 1 };
		for (int i = _fact.Count; i <= n; i++)
			_fact.Add(Mult(_fact[i - 1], i));
		return _fact[n];
	}

	static long[] _ifact = new long[0];
	static long InverseFact(int n)
	{
		long result;
		if (n < _ifact.Length && (result = _ifact[n]) != 0)
			return result;

		var inv = Inverse(Fact(n));
		if (n >= _ifact.Length) Resize(ref _ifact, _fact.Capacity);
		_ifact[n] = inv;
		return inv;
	}

	static long Fact(int n, int m)
	{
		var fact = Fact(n);
		if (m < n) fact = fact * InverseFact(n - m) % MOD;
		return fact;
	}

	static long Comb(int n, int k)
	{
		if (k <= 1) return k == 1 ? n : k == 0 ? 1 : 0;
		return Mult(Mult(Fact(n), InverseFact(k)), InverseFact(n - k));
	}

	public static long Combinations(long n, int k)
	{
		if (k <= 0) return k == 0 ? 1 : 0;  // Note: n<0 -> 0 unless k=0
		if (k + k > n) return Combinations(n, (int)(n - k));

		var result = InverseFact(k);
		for (long i = n - k + 1; i <= n; i++) result = result * i % MOD;
		return result;
	}
	#endregion

	#region Common
	partial void TestData();

	static void Swap<T>(ref T a, ref T b)
	{
		var tmp = a;
		a = b;
		b = tmp;
	}

	static int Bound<T>(T[] array, T value, bool upper = false)
		where T : IComparable<T>
	{
		int left = 0;
		int right = array.Length - 1;

		while (left <= right)
		{
			int mid = left + (right - left >> 1);
			int cmp = value.CompareTo(array[mid]);
			if (cmp > 0 || cmp == 0 && upper)
				left = mid + 1;
			else
				right = mid - 1;
		}
		return left;
	}

	public static int Gcd(int n, int m)
	{
		while (true)
		{
			if (m == 0) return n >= 0 ? n : -n;
			n %= m;
			if (n == 0) return m >= 0 ? m : -m;
			m %= n;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	static int BitCount(long y)
	{
		var x = unchecked((ulong)y);
		x -= (x >> 1) & 0x5555555555555555;
		x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
		x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f;
		return unchecked((int)((x * 0x0101010101010101) >> 56));
	}

	#endregion

	#region Fast IO
	#region  Input
	static Stream inputStream;
	static int inputIndex, bytesRead;
	static byte[] inputBuffer;
	static StringBuilder builder;
	const int MonoBufferSize = 4096;
	const char EOL = (char)10, DASH = (char)45, ZERO = (char)48;

	static void InitInput(Stream input = null, int stringCapacity = 16)
	{
		builder = new StringBuilder(stringCapacity);
		inputStream = input ?? Console.OpenStandardInput();
		inputIndex = bytesRead = 0;
		inputBuffer = new byte[MonoBufferSize];
	}

	static void ReadMore()
	{
		if (bytesRead < 0) throw new FormatException();
		inputIndex = 0;
		bytesRead = inputStream.Read(inputBuffer, 0, inputBuffer.Length);
		if (bytesRead > 0) return;
		bytesRead = -1;
		inputBuffer[0] = (byte)EOL;
	}

	static int Read()
	{
		if (inputIndex >= bytesRead) ReadMore();
		return inputBuffer[inputIndex++];
	}

	static T[] Na<T>(int n, Func<T> func, int z = 0)
	{
		n += z;
		var list = new T[n];
		for (int i = z; i < n; i++) list[i] = func();
		return list;
	}

	static int[] Ni(int n, int z = 0) => Na(n, Ni, z);

	static long[] Nl(int n, int z = 0) => Na(n, Nl, z);

	static string[] Ns(int n, int z = 0) => Na(n, Ns, z);

	static int Ni() => checked((int)Nl());

	static long Nl()
	{
		var c = SkipSpaces();
		bool neg = c == DASH;
		if (neg) { c = Read(); }

		long number = c - ZERO;
		while (true)
		{
			var d = Read() - ZERO;
			if (unchecked((uint)d > 9)) break;
			number = number * 10 + d;
			if (number < 0) throw new FormatException();
		}
		return neg ? -number : number;
	}

	static char[] Nc(int n)
	{
		var list = new char[n];
		for (int i = 0, c = SkipSpaces(); i < n; i++, c = Read()) list[i] = (char)c;
		return list;
	}

	static string Ns()
	{
		var c = SkipSpaces();
		builder.Clear();
		while (true)
		{
			if (unchecked((uint)c - 33 >= (127 - 33))) break;
			builder.Append((char)c);
			c = Read();
		}
		return builder.ToString();
	}

	static int SkipSpaces()
	{
		int c;
		do c = Read(); while (unchecked((uint)c - 33 >= (127 - 33)));
		return c;
	}

	static List<int>[] NewGraph(int n, int m = 0, int off = 0)
	{
		n += 1 + off;
		var g = new List<int>[n];
		for (int i = 0; i < n; i++)
			g[i] = new List<int>();

		for (int i = 0; i < m; i++)
		{
			int u = Ni() + off, v = Ni() + off;
			g[u].Add(v);
			g[v].Add(u);
		}

		return g;
	}

	static string ReadLine()
	{
		builder.Clear();
		while (true)
		{
			int c = Read();
			if (c < 32) { if (c == 10 || c <= 0) break; continue; }
			builder.Append((char)c);
		}
		return builder.ToString();
	}
	#endregion

	#region Output
	static Stream outputStream;
	static byte[] outputBuffer;
	static int outputIndex;

	static void InitOutput(Stream output = null)
	{
		outputStream = output ?? Console.OpenStandardOutput();
		outputIndex = 0;
		outputBuffer = new byte[65535];
	}

	static void WriteLine(object obj = null)
	{
		Write(obj);
		Write(EOL);
	}

	static void WriteLine(long number)
	{
		Write(number);
		Write(EOL);
	}

	static void Write(long signedNumber)
	{
		ulong number = unchecked((ulong)signedNumber);
		if (signedNumber < 0)
		{
			Write(DASH);
			number = unchecked((ulong)(-signedNumber));
		}

		Reserve(20 + 1); // 20 digits + 1 extra for sign
		int left = outputIndex;
		do
		{
			outputBuffer[outputIndex++] = (byte)(ZERO + number % 10);
			number /= 10;
		}
		while (number > 0);

		int right = outputIndex - 1;
		while (left < right)
		{
			byte tmp = outputBuffer[left];
			outputBuffer[left++] = outputBuffer[right];
			outputBuffer[right--] = tmp;
		}
	}

	static void Write(object obj)
	{
		if (obj == null) return;

		var s = obj.ToString();
		Reserve(s.Length);
		for (int i = 0; i < s.Length; i++)
			outputBuffer[outputIndex++] = (byte)s[i];
	}

	static void Write(char c)
	{
		Reserve(1);
		outputBuffer[outputIndex++] = (byte)c;
	}

	static void Write(byte[] array, int count)
	{
		Reserve(count);
		Copy(array, 0, outputBuffer, outputIndex, count);
		outputIndex += count;
	}

	static void Reserve(int n)
	{
		if (outputIndex + n <= outputBuffer.Length)
			return;

		Dump();
		if (n > outputBuffer.Length)
			Resize(ref outputBuffer, Max(outputBuffer.Length * 2, n));
	}

	static void Dump()
	{
		outputStream.Write(outputBuffer, 0, outputIndex);
		outputIndex = 0;
	}

	static void Flush()
	{
		Dump();
		outputStream.Flush();
	}

	#endregion
	#endregion

	#region Main

	public static void Main()
	{
		AppDomain.CurrentDomain.UnhandledException += (sender, arg) =>
		{
			Flush();
			var e = (Exception)arg.ExceptionObject;
			Console.Error.WriteLine(e);
			var line = new StackTrace(e, true).GetFrames()
				.Select(x => x.GetFileLineNumber()).FirstOrDefault(x => x != 0);
			var wait = line % 300 * 10 + 5;
			var process = Process.GetCurrentProcess();
			while (process.TotalProcessorTime.TotalMilliseconds > wait && wait < 3000) wait += 1000;
			while (process.TotalProcessorTime.TotalMilliseconds < Min(wait, 3000)) ;
			Environment.Exit(1);
		};

		InitInput(Console.OpenStandardInput());
		InitOutput(Console.OpenStandardOutput());
#if __MonoCS__ && !C7
        var thread = new System.Threading.Thread(()=>new Solution().Solve());
        var f = BindingFlags.NonPublic | BindingFlags.Instance;
        var t = thread.GetType().GetField("internal_thread", f).GetValue(thread);
        t.GetType().GetField("stack_size", f).SetValue(t, 32 * 1024 * 1024);
        thread.Start();
        thread.Join();
#else
		new Solution().Solve();
#endif
		Flush();
		Console.Error.WriteLine(Process.GetCurrentProcess().TotalProcessorTime);
	}
	#endregion
	#endregion
}


using System;
using System.Linq;
public class Test
{
    public static void Main()
    {
        // your code goes here
        string[] arr = Console.ReadLine().Trim().Split();
        int n = int.Parse(arr[0]);
        int t = int.Parse(arr[2]);
        double p = double.Parse(arr[1]);
        double[,] dp = new double[t + 1, n + 1];

    }
}


using System;
using System.Globalization;
using System.IO;
using System.Text;

namespace Ilya_and_Escalator
{
    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[] ss = reader.ReadLine().Split(' ');
            int n = int.Parse(ss[0]);
            int t = int.Parse(ss[2]);
            double p = double.Parse(ss[1], CultureInfo.InvariantCulture);
            double q = 1 - p;
            var nn = new double[n + 1];
            nn[0] = 1;

            for (int i = 0; i < t; i++)
            {
                nn[n] += p*nn[n - 1];

                for (int j = n - 1; j > 0; j--)
                {
                    nn[j] = q*nn[j] + p*nn[j - 1];
                }

                nn[0] *= q;
            }

            double sum = 0;

            for (int i = 1; i <= n; i++)
            {
                sum += i*nn[i];
            }

            writer.WriteLine(sum.ToString("#0.0000000", CultureInfo.InvariantCulture));
            writer.Flush();
        }
    }
}


using System;
using System.Linq;
using System.Globalization;
public class Test
{
    public static void Main()
    {
        // your code goes here
        string[] arr = Console.ReadLine().Trim().Split();
        int n = int.Parse(arr[0]);
        int t = int.Parse(arr[2]);
        double p = double.Parse(arr[1],CultureInfo.InvariantCulture);
        double[,] dp = new double[t + 1, n + 1];
        dp[1, 0] = (double)1 - p;
        dp[1, 1] = p;
        for (int i = 2; i <= t; i++)
        {
            for (int j = 0; j <= n; j++)
            {
                //if this guy is not goes
                double p1 = dp[i - 1, j] * ((double)1 - p);
                if (j - 1 >= 0)
                {
                    p1 += dp[i - 1, j - 1] * p;
                }
                dp[i, j] += p1;
            }
        }
        double expected = 0; //
        for (int i = 1; i <= n; i++)
        {
            expected += dp[t, i] * i;
        }
        Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:0.000000000000}", expected));
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace ed32e
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void solution()
        {
            #region SOLUTION

            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var a = readIntArray();

            var fh = n / 2;
            if (n % 2 == 1)
            {
                fh++;
            }
            var sh = n / 2;

            var mv = 0;
            for (int i = 0; i < fh; i++)
            {
                mv &= 1 << i;
            }

            var arr = new long[mv + 1];
            for (int i = 0; i <= mv; i++)
            {
                arr[i] = sum(i, a, m, 0);
            }

            Array.Sort(arr);
            var max = arr[arr.Length - 1];

            var sm = 0;
            //for (int i = mv; i < n; i++)
            //{
            //    sm &= 1 << i;
            //}

            for (int i = 0; i <= sh; i++)
            {
                sm &= 1 << i;
            }

            //var smin = mv + 1;
            var res = long.MinValue;
            for (int i = 0; i <= sm; i++)
            {
                var val = sum(i, a, m, mv + 1);
                var nr = (val + max) % m;
                if (nr > res)
                {
                    res = nr;
                }

                var req = m - val - 1;
                if (req <= 0)
                {
                    continue;
                }

                var l = 0;
                var r = arr.Length - 1;
                while (true)
                {
                    if (l == r)
                    {
                        break;
                    }

                    var mid = l + (r - l + 1) / 2;
                    var vv = arr[mid];
                    if (vv <= req)
                    {
                        l = mid;
                    }
                    else
                    {
                        r = mid - 1;
                    }
                }

                if (arr[l] <= req)
                {
                    if (val + arr[l] > res)
                    {
                        res = val + arr[l];
                    }
                }
            }

            Console.WriteLine(res);
            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static long sum(int pattern, int[] a, int m, int start)
        {
            var res = 0;
            for (int i = 0; i < 20; i++)
            {
                if ((pattern & (1 << i)) != 0)
                {
                    res += a[i + start];
                    res %= m;
                }
            }

            return res;
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using Pi = Pair<int, int>;

class Solver
{
    public Scanner sc;
    public void Solve()
    {
        int N, M;
        sc.Make(out N, out M);
        var A = sc.ArrInt;
        var L = Create(2, () => new HashSet<int>());
        for(int k = 0; k < 2; k++)
        {
            int[] a;
            if (k == 0) a = A.Take(N / 2).ToArray();
            else a = A.Skip(N / 2).ToArray();
            for(int j = 0; j < (1 << a.Length); j++)
            {
                var sum = 0;
                for (int l = 0; l < a.Length; l++)
                    if ((1 & j >> l) == 1) { sum += a[l]; if (sum >= M) sum -= M; }
                L[k].Add(sum);
            }
        }
        var dat = Create(2, id => {
            var r = new int[L[id].Count];
            var now = 0;
            foreach (var d in L[id]) r[now++] = d;
            Array.Sort(r);
            return r;
        });
        var max = 0;
        var idx = 0;
        for(int i = 0; i < dat[0].Length; i++)
        {
            while ((dat[1][(idx + 1) % dat[1].Length] + dat[0][i]) % M > (dat[1][idx] + dat[0][i]) % M)
            {
                idx++;if (idx >= dat[1].Length) idx -= dat[1].Length;
            }
            chmax(ref max, (dat[1][idx] + dat[0][i]) % M);
        }
        Console.WriteLine(max);
    }
}

#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        var sol = new Solver() { sc = new Scanner() };
        //var th = new Thread(sol.Solve, 1 << 26);th.Start();th.Join();
        sol.Solve();
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    public void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
    //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}
public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; }
}
#endregion


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace ed32e
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void solution()
        {
            #region SOLUTION

            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var a = readIntArray();

            var fh = n / 2;
            if (n % 2 == 1)
            {
                fh++;
            }
            var sh = n / 2;

            var mv = 0;
            for (int i = 0; i < fh; i++)
            {
                mv |= 1 << i;
            }

            var arr = new long[mv + 1];
            for (int i = 0; i <= mv; i++)
            {
                arr[i] = sum(i, a, m, 0);
            }

            Array.Sort(arr);
            var max = arr[arr.Length - 1];

            var sm = 0;
            //for (int i = mv; i < n; i++)
            //{
            //    sm &= 1 << i;
            //}

            for (int i = 0; i < sh; i++)
            {
                sm |= 1 << i;
            }

            //var smin = mv + 1;
            var res = long.MinValue;
            for (int i = 0; i <= sm; i++)
            {
                var val = sum(i, a, m, fh);
                var nr = (val + max) % m;
                if (nr > res)
                {
                    res = nr;
                }

                var req = m - val - 1;
                //if (req <= 0)
                //{
                //    continue;
                //}

                var l = 0;
                var r = arr.Length - 1;
                while (true)
                {
                    if (l == r)
                    {
                        break;
                    }

                    var mid = l + (r - l + 1) / 2;
                    var vv = arr[mid];
                    if (vv <= req)
                    {
                        l = mid;
                    }
                    else
                    {
                        r = mid - 1;
                    }
                }

                if (arr[l] <= req)
                {
                    if (val + arr[l] > res)
                    {
                        res = val + arr[l];
                    }
                }
            }

            Console.WriteLine(res);
            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static long sum(int pattern, int[] a, int m, int start)
        {
            var res = 0;
            for (int i = 0; i < 20; i++)
            {
                if ((pattern & (1 << i)) != 0)
                {
                    res += a[i + start];
                    res %= m;
                }
            }

            return res;
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


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

namespace покупка_телевизора
{
    class Program
    {
       static long Nod(long a, long b)
        {
            if(a<b)
            {
                long temp = a;
                a = b;
                b = temp;
            }
            while(b!=0)
            {
                if (a < b)
                {
                    long t = a;
                    a = b;
                    b = t;
                }
                long temp = b;
                b = a - b;
                a = temp;
            }
            return a;
        }
        static void Main(string[] args)
        {
            long a, b, x, y;
            string[] s = Console.ReadLine().Split(' ');
            a = long.Parse(s[0]);
            b = long.Parse(s[1]);
            x = long.Parse(s[2]);
            y = long.Parse(s[3]);
            long NOD = Nod(x, y);
            x /= NOD;
            y /= NOD;
            long answer;
            answer = a / x;
            if (b / y < answer)
                answer = b / y;
            Console.WriteLine(answer);
        }
    }
}


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

namespace bla
{
    class Program
    {
        static void Main()
        {
            string[] s = Console.ReadLine().Split();
            long a = long.Parse(s[0]);
            long b = long.Parse(s[1]);
            long x = long.Parse(s[2]);
            long y = long.Parse(s[3]);

            long gcd = GCD(x, y);
            x /= gcd;
            y /= gcd;

            Console.WriteLine(Math.Min(b/y, a/x));
        }

        public static long GCD(long a, long b)
        {
            while (b != 0)
            {
                long t = a;
                a = b;
                b = t % b;
            }
            return a;
        }
    }
}


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

namespace Test
{
    class IOHelper : IDisposable
    {
        StreamReader reader;
        StreamWriter writer;

        public IOHelper(string inputFile, string outputFile, Encoding encoding)
        {
            StreamReader iReader;
            StreamWriter oWriter;
            if (inputFile == null)
                iReader = new StreamReader(Console.OpenStandardInput(), encoding);
            else
                iReader = new StreamReader(inputFile, encoding);

            if (outputFile == null)
                oWriter = new StreamWriter(Console.OpenStandardOutput(), encoding);
            else
                oWriter = new StreamWriter(outputFile, false, encoding);

            reader = iReader;
            writer = oWriter;

            curLine = new string[] { };
            curTokenIdx = 0;
        }

        string[] curLine;
        int curTokenIdx;

        char[] whiteSpaces = new char[] { ' ', '\t', '\r', '\n' };

        public string ReadNextToken()
        {
            if (curTokenIdx >= curLine.Length)
            {
                //Read next line
                string line = reader.ReadLine();
                if (line != null)
                    curLine = line.Split(whiteSpaces, StringSplitOptions.RemoveEmptyEntries);
                else
                    curLine = new string[] { };
                curTokenIdx = 0;
            }

            if (curTokenIdx >= curLine.Length)
                return null;

            return curLine[curTokenIdx++];
        }

        public int ReadNextInt()
        {
            return int.Parse(ReadNextToken());
        }

        public double ReadNextDouble()
        {
            var nextToken = ReadNextToken();
            var result = 0.0;
            nextToken = nextToken.Replace(".", System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
            result = double.Parse(nextToken);
            return result;
        }

        public void Write(string stringToWrite)
        {
            writer.Write(stringToWrite);
        }

        public void WriteLine(string stringToWrite)
        {
            writer.WriteLine(stringToWrite);
        }

        public void WriteLine(double valueToWrite)
        {
            long intPart = (long)valueToWrite;
            double fracPart = valueToWrite - intPart;
            var fracPartStr = fracPart.ToString();
            if (fracPartStr.Length > 1)
                fracPartStr = fracPartStr.Substring(2);
            var strToWrite = string.Format("{0}.{1}", intPart, fracPartStr);
            writer.WriteLine(strToWrite);
        }

        public void Dispose()
        {
            try
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
            catch { };
        }

        public void Flush()
        {
            if (writer != null)
            {
                writer.Flush();
            }
        }
    }

    class Program
    {
        protected IOHelper ioHelper;

        long a,b,x,y;

        long cmmdc(long a, long b)
        {
            while(b!=0)
            {
                long t = b;
                b = a % b;
                a = t;
            }

            return a;
        }

        public void Solve()
        {
            a = long.Parse(ioHelper.ReadNextToken());
            b = long.Parse(ioHelper.ReadNextToken());
            x = long.Parse(ioHelper.ReadNextToken());
            y = long.Parse(ioHelper.ReadNextToken());

            long cmm = cmmdc(x, y);
            x /= cmm;
            y /= cmm;

            long mulX = a / x;
            long mulY = b / y;

            long res = Math.Min(mulX, mulY);

            ioHelper.WriteLine(res.ToString());
            ioHelper.Flush();

            //Console.ReadKey();
        }

        public Program(string inputFile, string outputFile)
        {
            ioHelper = new IOHelper(inputFile, outputFile, Encoding.Default);
            Solve();
            ioHelper.Dispose();
        }

        static void Main(string[] args)
        {
            Program myProgram = new Program(null, null);
        }
    }
}


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

namespace Codeforces
{
    class C
    {
        private static ThreadStart s_threadStart = new C().Go;

        private void Go()
        {
            int N = GetInt();
            List<int> data = GetIntArr(N);

            int[,] dp = new int[N, 2];
            dp[N - 1, 0] = data[N - 1];
            dp[N - 1, 1] = 0;
            for (int i = N-2; i >= 0; i--)
            {
                if (dp[i + 1, 0] < data[i] + dp[i + 1, 1])
                {
                    dp[i, 0] = data[i] + dp[i + 1, 1];
                    dp[i, 1] = dp[i + 1, 0];
                }
                else
                {
                    dp[i, 1] = data[i] + dp[i + 1, 1];
                    dp[i, 0] = dp[i + 1, 0];
                }
            }

            Wl(dp[0, 1] + " " + dp[0, 0]);
        }

        #region Template

        private static StringBuilder output = new StringBuilder();

        public static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            output.Length = 0;
            Thread main = new Thread(new ThreadStart(s_threadStart), 512 * 1024 * 1024);
            timer.Start();
            main.Start();
            main.Join();
            Console.Write(output);
            timer.Stop();
            Console.Error.WriteLine(timer.ElapsedMilliseconds);
        }

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

            return ioEnum.Current;
        }

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

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

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

        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)
        {
            W(o);
            output.Append(Console.Out.NewLine);
        }

        private static void Wl<T>(IEnumerable<T> enumerable)
        {
            W(enumerable);
            output.Append(Console.Out.NewLine);
        }

        private static void W<T>(T o)
        {
            if (o is double)
            {
                Wd((o as double?).Value, "");
            }
            else if (o is float)
            {
                Wd((o as float?).Value, "");
            }
            else
                output.Append(o.ToString());
        }

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

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

        #endregion
    }
}


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

// (づ°ω°)づﾐ★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    private const int MAX = 500000;

    public void Solve()
    {
        int n = ReadInt();
        int d = ReadInt();
        var a = ReadIntArray();

        var dp = new bool[MAX + 1];
        dp[0] = true;
        for (int i = 0; i < n; i++)
        {
            for (int j = MAX; j >= 0; j--)
                if (dp[j])
                    dp[j + a[i]] = true;
        }

        int x = 0;
        int ans = 0;
        while (true)
        {
            int y = Math.Min(x + d, MAX);
            while (!dp[y])
                y--;
            if (x == y)
                break;
            ans++;
            x = y;
        }

        Write(x, ans);
    }

    #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("subsequences.in");
        //writer = new StreamWriter("subsequences.out");
#endif
        try
        {
//            var thread = new Thread(new Solver().Solve, 1024 * 1024 * 256);
//            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.Collections.Generic;
using System.Linq;

namespace Solution {

    class Solution {

        class StdIn {
            int currPos = 0;
            string[] tokens = new string[0];

            private string getNextToken() {
                if (currPos < tokens.Length) return tokens[currPos++];
                currPos = 0;
                tokens = Console.ReadLine().Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                return tokens[currPos++];
            }

            public int nextInt() {
                return int.Parse(getNextToken());
            }

            public string nextString() {
                return getNextToken();
            }

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

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

        public static void swap<T>(ref T a, ref T b) {
            T c = a;
            a = b;
            b = c;
        }

        static int countPowers(int p, int n) {
            int result = 0;
            int curr = 1;
            while (n / p >= curr) {
                ++result;
                curr *= p;
                Used.Add(curr);
            }
            return result;
        }

        static HashSet<int> Used = new HashSet<int>();
        static Dictionary<int, int> D = new Dictionary<int, int>();

        static int bitmask(ref List<int> p) {
            int result = 0;
            for (int i = 0; i < p.Count; ++i)
                result = 2 * result + p[i];
            return result;
        }

        static int fun(ref List<int> p) {
            if (D.ContainsKey(bitmask(ref p))) {
                return D[bitmask(ref p)];
            }
            HashSet<int> s = new HashSet<int>();
            for (int i = 0; i < p.Count; ++i) if (p[i] == 1) {
                List<int> n = new List<int>(p);
                for (int j = 0; j < n.Count; ++j) if ((j + 1) % (i + 1) == 0) n[j] = 0;
                s.Add(fun(ref n));
            }
            int result = 0;
            while (s.Contains(result)) ++result;
            D[bitmask(ref p)] = result;
            return result;
        }

        static int getSprague(int len) {
            if (len == 2) return 2;
            // SG for group of powers
            D.Clear();
            D[0] = 0;

            List<int> p = new List<int>();
            for (int i = 0; i < len; ++i) p.Add(1);
            //Console.WriteLine(len + " " + fun(ref p));
            return fun(ref p);
        }

        public static void Main(string[] args) {
            StdIn std = new StdIn();

            int n = std.nextInt();

            int ans = 0;

            int totcnt = n;

            for (int i = 2; i * i <= n; ++i) if (!Used.Contains(i)) {
                int cnt = countPowers(i, n);
                totcnt -= cnt;
                ans ^= getSprague(cnt);
            }

            if (totcnt % 2 > 0) ans ^= 1;

            if (ans > 0) Console.WriteLine("Vasya");
            else Console.WriteLine("Petya");

            //Console.ReadLine();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using static Template;
using static System.Console;
using static System.Convert;
using static System.Math;
using Pi = Pair<int, int>;

class Solver
{
    int N;
    string s;
    ModInt[][] dp;
    bool[][] use;
    public void Solve(Scanner sc)
    {
        var N = sc.Int;
        dp = Create(N + 1, () => new ModInt[1 << 20]);
        use = Create(N + 1, () => new bool[1 << 20]);

    }
    /*ModInt memo(int s,int i)
    {
        var ct = 0;
        for (var j = 0; j < 20; j++)
            ct += 1 & s >> j;
        var rt = 0;
        if (i == N)
        {
            if (ct != 0 && (1 << ct) - 1 == s) return 1;
            return 0;
        }

    }*/
}

public struct ModInt
{
    public const long MOD = (int)1e9 + 7;
    //public const long MOD = 998244353;
    public long Value { get; set; }
    public ModInt(long n = 0) { Value = n; }
    private static ModInt[] fac;//階乗
    private static ModInt[] inv;//逆数
    private static ModInt[] facinv;//1/(i!)
    public override string ToString() => Value.ToString();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator +(ModInt l, ModInt r)
    {
        l.Value += r.Value;
        if (l.Value >= MOD) l.Value -= MOD;
        return l;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator -(ModInt l, ModInt r)
    {
        l.Value -= r.Value;
        if (l.Value < 0) l.Value += MOD;
        return l;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator *(ModInt l, ModInt r) => new ModInt(l.Value * r.Value % MOD);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator /(ModInt l, ModInt r) => l * Pow(r, MOD - 2);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static implicit operator long(ModInt l) => l.Value;
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static implicit operator ModInt(long n)
    {
        n %= MOD; if (n < 0) n += MOD;
        return new ModInt(n);
    }

    public static ModInt Pow(ModInt m, long n)
    {
        if (n == 0) return 1;
        if (n % 2 == 0) return Pow(m * m, n >> 1);
        else return Pow(m * m, n >> 1) * m;
    }

    public static void Build(int n)
    {
        fac = new ModInt[n + 1];
        facinv = new ModInt[n + 1];
        inv = new ModInt[n + 1];
        inv[1] = 1;
        fac[0] = fac[1] = 1;
        facinv[0] = facinv[1] = 1;
        for (var i = 2; i <= n; i++)
        {
            fac[i] = fac[i - 1] * i;
            inv[i] = MOD - inv[MOD % i] * (MOD / i);
            facinv[i] = facinv[i - 1] * inv[i];
        }
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt Fac(ModInt n) => fac[n];
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt Inv(ModInt n) => inv[n];
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt FacInv(ModInt n) => facinv[n];
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt Comb(ModInt n, ModInt r)
    {
        if (n < r) return 0;
        if (n == r) return 1;
        var calc = fac[n];
        calc = calc * facinv[r];
        calc = calc * facinv[n - r];
        return calc;
    }
}
#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver().Solve(new Scanner());
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T>
    { if (a.CompareTo(b) == 1) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T>
    { if (a.CompareTo(b) == -1) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b)
    { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static T[] Create<T>(int n, Func<T> f)
    {
        var rt = new T[n];
        for (var i = 0; i < rt.Length; ++i)
            rt[i] = f();
        return rt;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static T[] Create<T>(int n, Func<int, T> f)
    {
        var rt = new T[n];
        for (var i = 0; i < rt.Length; ++i)
            rt[i] = f(i);
        return rt;
    }
    public static T[] Copy<T>(this T[] A) => Create(A.Length, i => A[i]);
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}

public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    public Pair<T1, T2> PairMake<T1, T2>() => new Pair<T1, T2>(Next<T1>(), Next<T2>());
    public Pair<T1, T2, T3> PairMake<T1, T2, T3>() => new Pair<T1, T2, T3>(Next<T1>(), Next<T2>(), Next<T3>());
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
}

public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Tie(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Tie(out T1 a, out T2 b, out T3 c) { Tie(out a, out b); c = v3; }
}
#endregion


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
{
    static Scanner cin;
    public Myon() { }
    public static int Main()
    {
        //Console.SetOut(new Printer(Console.OpenStandardOutput()));
        cin = new Scanner();
        new Myon().calc();
        return 0;
    }

    int ans;

    List<int>[] es;
    int h;

    public void calc2()
    {
        ans = -1;
        qnum = 0;
        h = cin.nextInt();
        es = new List<int>[1 << h];
        int fq = 0;
        getQuestion(fq);
        if (es[fq].Count != 2)
        {
            if (es[fq].Count == 3)
            {
                //2つ試す
                int LenA = getLength(es[fq][0], fq);
                int LenB = getLength(es[fq][1], fq);
                int start = fq;
                if (LenA < LenB)
                {
                    start = getStep(es[fq][1], fq, (LenB - LenA) / 2 - 1);
                }
                if (LenB < LenA)
                {
                    start = getStep(es[fq][0], fq, (LenA - LenB) / 2 - 1);
                }
                int height = (LenB + LenA) / 2 + 1;

                if (es[start].Count != 2)
                {
                    foreach (var item in es[start])
                    {
                        if (es[item] != null) continue;
                        getNext(height + 1, item, start);
                        break;
                    }
                }

            }
            else
            {
                getNext(2, es[fq][0], fq);
            }
        }
        Console.WriteLine("! {0}", ans + 1);
    }

    bool debug = false;

    void getNext(int nowHeight, int a, int pre)
    {
        if(debug) Console.WriteLine("Now Checking... " + nowHeight + " " + a + " " + pre);
        getQuestion(a);
        if (ans != -1) return;
        if (nowHeight == h) return;
        if(nowHeight == h - 1 && !debug)
        {
            if(debug) Console.WriteLine("Find -1 Mode");
            foreach (var item in es[a])
            {
                getQuestion(item);
                if (ans != -1) return;
            }
            return;
        }
        if (nowHeight == h - 2 && !debug)
        {
            if (debug) Console.WriteLine("Find -2 Mode");
            foreach (var item in es[a])
            {
                if (item != pre)
                {
                    getQuestion(item);
                    if (ans != -1) return;
                    foreach (var i2 in es[item])
                    {
                        if (i2 != a) getQuestion(i2);
                        if (ans != -1) return;
                    }
                }
            }
            return;
        }

        foreach (var item in es[a])
        {
            if (item == pre) continue;
            int nextLen = getLength(item, a);
            int preLen = nowHeight - 1;
            int nextStart = getStep(a, pre, (nextLen - preLen) / 2);
            int nextHeight = (preLen + nextLen) / 2 + 1;
            if (es[nextStart].Count == 2) return;

            int nextA = -1;
            foreach (var i2 in es[nextStart])
            {
                if(es[i2] == null)
                {
                    nextA = i2;
                }
            }

            if (debug)
            {
                Console.WriteLine("NextStart:{0} NextHeight:{1} nextLen:{2} preLen:{3}, nextA:{4}", nextStart, nextHeight, nextLen, preLen, nextA);
            }

            getNext(nextHeight + 1, nextA, nextStart);
            return;
        }
    }

    int getStep(int a, int ng, int step)
    {
        if (step == 0) return a;
        foreach (var item in es[a])
        {
            if (item != ng && es[item] != null) return getStep(item, a, step - 1);
        }
        return -1;
    }

    int getLength(int a, int ng)
    {
        getQuestion(a);
        if (es[a].Count == 2) return h;
        if (es[a].Count == 1) return 1;
        foreach (var item in es[a])
        {
            if(item != ng)
            {
                return getLength(item, a) + 1;
            }
        }
        return -1;
    }

    int qnum = 0;
    List<int> getQuestion(int a)
    {
        if (es[a] != null) return es[a];
        List<int> l = new List<int>();
        if(qnum >= 16)
        {
            l.Add(-1);
            l.Add(-1);
            ans = a;
            return es[a] = l;
        }
        Console.WriteLine("? {0}", a + 1);
        qnum++;
        int num = cin.nextInt();
        for (int i = 0; i < num; i++)
        {
            l.Add(cin.nextInt() - 1);
        }
        if (num == 2)
        {
            ans = a;
        }
        return es[a] = l;
    }

    public void calc()
    {
        int T = cin.nextInt();
        for (int i = 0; i < T; i++)
        {
            calc2();
        }
    }

}

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

class Scanner
{
    string[] s;
    int i;

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

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

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

    public int nextInt()
    {
        return int.Parse(next());
    }

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

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

}