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

class Program
{

    void solve()
    {
        int[] cnt = new int[3];
        int rem=0;
        for (int i = 0; i < 3; i++)
            rem+=cnt[i] = nextInt();
        int at = 0;
        int res = 0;
        while (rem > 0)
        {
            res++;
            rem -= Math.Min(2, cnt[at]);
            cnt[at] -= Math.Min(2, cnt[at]);
            at = (at + 1) % 3;

        }
        println(res + 29);
    }

    ////////////
    private void println(int[] ar)
    {
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i]);
            else
                print(ar[i] + " ");
        }
    }
    private void println(int[] ar, bool add)
    {
        int A = 0;
        if (add)
            A++;
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i] + A);
            else
                print((ar[i] + A) + " ");
        }
    }

    private void println(string Stringst)
    {
        Console.WriteLine(Stringst);
    }
    private void println(char charnum)
    {
        Console.WriteLine(charnum);
    }
    private void println(int Intnum)
    {
        Console.WriteLine(Intnum);
    }
    private void println(long Longnum)
    {
        Console.WriteLine(Longnum);
    }
    private void println(double Doublenum)
    {
        string s = Doublenum.ToString(CultureInfo.InvariantCulture);
        Console.WriteLine(s);
    }

    private void print(string Stringst)
    {
        Console.Write(Stringst);
    }
    private void print(int Intnum)
    {
        Console.Write(Intnum);
    }
    private void print(char charnum)
    {
        Console.Write(charnum);
    }
    private void print(long Longnum)
    {
        Console.Write(Longnum);
    }
    private void print(double Doublenum)
    {
        Console.Write(Doublenum);
    }

    string[] inputLine = new string[0];
    int inputInd = 0;
    string nextLine()
    {
        return Console.ReadLine();
    }
    void readInput()
    {
        if (inputInd != inputLine.Length)
            throw new Exception();
        inputInd = 0;
        inputLine = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (inputLine.Length == 0)
            readInput();

    }
    int nextInt()
    {
        return int.Parse(nextString());
    }
    long nextLong()
    {
        return long.Parse(nextString());
    }
    double nextDouble()
    {
        return double.Parse(nextString());
    }
    string nextString()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return inputLine[inputInd++];
    }
    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        new Program().solve();
    }
}


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

namespace Contest.A
{
    class Program
    {
        /////////////////////

        public static T Read<T>()
        {
            return (T)Convert.ChangeType(Console.ReadLine(), typeof(T));
        }

        public static List<T> ReadList<T>(char[] delimiters = null)
        {
            var line = Read<string>();
            var split = line.Split(delimiters ?? new[] { ' ' });
            var list = split.Select(item => (T)Convert.ChangeType(item, typeof(T))).ToList();
            return list;
        }

        public static List<KeyValuePair<int, T>> ReadIndexedList<T>(char[] delimiters = null)
        {
            var line = Read<string>();
            var split = line.Split(delimiters ?? new[] { ' ' });
            var list = split.Select((item, index) => new KeyValuePair<int, T>(index + 1, (T)Convert.ChangeType(item, typeof(T)))).ToList();
            return list;
        }

        public static void ReadFromFile()
        {
            Console.SetIn(new StreamReader(@"..\..\input.txt"));
        }

        ///////////////////////////////////

        static void Main(string[] args)
        {
            try
            {
                var list = ReadList<int>();
                int r = list[0];
                int g = list[1];
                int b = list[2];

                int rr = (int) Math.Ceiling(r/2d);
                int gg = (int) Math.Ceiling(g / 2d);
                int bb = (int) Math.Ceiling(b / 2d);

                int res = 30 + Max(0 + (rr - 1)*3 , 1 + (gg - 1)*3 , 2 + (bb - 1)*3);
                Console.WriteLine(res);
            }
            catch
            {
                Console.Write("ERROR");
            }
        }

        private static int Max(int i, int i1, int i2)
        {
            return Math.Max(Math.Max(i, i1), i2);
        }
    }
}


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

class ProblemA
{
    static void Main(string[] args)
    {
        string[] tokens = Console.ReadLine().Split(' ');
        int r = int.Parse(tokens[0]), g = int.Parse(tokens[1]), b = int.Parse(tokens[2]);
        Console.WriteLine(30 + Math.Max(((r + 1) / 2 - 1) * 3, Math.Max(1 + ((g + 1) / 2 - 1) * 3, 2 + ((b + 1) / 2 - 1) * 3)));
    }
}


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

public class CF_Cableway
{
    public static void Main(string[] args)
    {
        string[] line = Console.ReadLine().Split();
        int[] S = new int[3] { int.Parse(line[0]), int.Parse(line[1]), int.Parse(line[2]) };
        int t = 0;
        int c = 0;
        while (true)
        {
            if (S[c] > 0)
            {
                S[c] -= 2;
                if (S[c] < 0) S[c] = 0;
                if (S[0] == 0 && S[1] == 0 && S[2] == 0) break;
            }
            ++t;
            ++c;
            c %= 3;
        }

        Console.WriteLine((30 + t).ToString());
        Console.ReadLine();
    }
}


using System;
using System.Linq;

namespace TaskA
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] rgb = Console.ReadLine().Split(' ').Select(str => int.Parse(str)).ToArray();
            int rtime = 0;
            if (rgb[0] > 0)
            {
                int g = (rgb[0] - 1) / 2 + 1;
                rtime = 30 + 3 * (g - 1);
            }

            int gtime = 0;
            if (rgb[1] > 0)
            {
                int g = (rgb[1] - 1) / 2 + 1;
                gtime = 31 + 3 * (g - 1);
            }

            int btime = 0;
            if (rgb[2] > 0)
            {
                int g = (rgb[2] - 1) / 2 + 1;
                btime = 32 + 3 * (g - 1);
            }

            int time = Math.Max(rtime, Math.Max(gtime, btime));
            Console.WriteLine(time);
        }
    }
}


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

namespace prA {

    class Program {
#if ONLINE_JUDGE
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), System.Text.Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), System.Text.Encoding.ASCII, 1024 * 10);
#else
        private static readonly StreamWriter writer = new StreamWriter(@"..\..\output");
        private static readonly StreamReader reader = new StreamReader(@"..\..\input");
#endif
        static void Main(string[] args) {
            int r = Next();
            int g = Next();
            int b = Next();
            int lastTime = -1;
            do {
                lastTime++;
                r = Math.Max(r - 2, 0);
                if(r + g + b > 0) {
                    lastTime++;
                    g = Math.Max(g - 2, 0);
                    if(r + g + b > 0) {
                        lastTime++;
                        b = Math.Max(b - 2, 0);
                    }
                }
            } while(r + g + b > 0);
            writer.Write(lastTime + 30);

            writer.Flush();
#if !ONLINE_JUDGE
            writer.Close();
#endif
        }
        private static int Next() {
            int c;
            int res = 0;
            do {
                c = reader.Read();
                if(c == -1)
                    return res;
            } while(c != '-' && (c < '0' || c > '9'));
            int sign = 1;
            if(c == '-') {
                sign = -1;
                c = reader.Read();
            }
            res = c - '0';
            while(true) {
                c = reader.Read();
                if(c < '0' || c > '9')
                    return res * sign;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


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

namespace camp
{
    class Program
    {
        static void Main(string[] args)
        {
            int [] arr = new int[3];
            arr = Console.ReadLine().Split(' ').Select(c => int.Parse(c)).ToArray();
            int sum = arr[0] + arr[1] + arr[2];
            int k = -1;
            while (sum > 0)
            {
                k++;
                if (k % 3 == 0) arr[0] -= 2;
                if (k % 3 == 1) arr[1] -= 2;
                if (k % 3 == 2) arr[2] -= 2;
                if (arr[0] < 0) arr[0] = 0;
                if (arr[1] < 0) arr[1] = 0;
                if (arr[2] < 0) arr[2] = 0;
                sum = arr[0] + arr[1] + arr[2];
            }
            Console.WriteLine(k+30);

        }
    }
}


using System;
using System.Linq;

namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] c = Console.ReadLine().Split().Select(x =>(int)Math.Ceiling(int.Parse(x)/2.0)).ToArray();
            int rez = 30;
            if (c[0] > c[1] && c[0] > c[2])
                rez += c[0] * 3 - 3;
            else if (c[1] >= c[0] && c[1] > c[2])
                rez += c[1] * 3 - 2;
            else if (c[2] >= c[0] && c[2] >= c[1])
                rez += c[2] * 3 - 1;

            Console.WriteLine(rez);
        }
    }
}


using System;

namespace Task1 {
    internal class Program {
        private static void Main(string[] args) {
            string s = Console.ReadLine();
            string[] ss = s.Split(' ');
            int r = int.Parse(ss[0]);
            int g = int.Parse(ss[1]);
            int b = int.Parse(ss[2]);
            int current = 0;
            while (r + g + b > 0) {
                if (current%3 == 0) r = Math.Max(0, r - 2);
                else if (current%3 == 1) g = Math.Max(0, g - 2);
                else b = Math.Max(0, b - 2);
                current++;
            }
            Console.WriteLine(current + 29);
        }
    }
}


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[3];
            string[] str = Console.ReadLine().Split(' ');
            a[0] = Int32.Parse(str[0]);
            a[1] = Int32.Parse(str[1]);
            a[2] = Int32.Parse(str[2]);
            int x = (a[0] + a[1] + a[2]);
            int i = 29;
            int color = 0;
            while (x>0)
            {
                if (color > 2) { color = 0; }
                if (a[color] > 2) { a[color] -= 2; } else { a[color] = 0; }
                x = a[0] + a[1] + a[2];
                i++;
                color++;
            }
            Console.WriteLine(i.ToString());
        }
    }
}


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

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

        private static void Main(string[] args)
        {
            int r = Next(), g = Next(), b = Next();

            int max = 3*((r + 1)/2 - 1);
            max = Math.Max(max, 3*((g + 1)/2 - 1) + 1);
            max = Math.Max(max, 3*((b + 1)/2 - 1) + 2);

            writer.WriteLine(max + 30);
            writer.Flush();
        }

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


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

namespace first
{
    class Program
    {
        static TextReader tr;
        static void cin(out int value)
        {
            if (tr == null) tr = Console.In;
            StringBuilder sb = new StringBuilder();
            while (tr.Peek() == (char)(' ') || tr.Peek() == 13 || tr.Peek() == 10)
                tr.Read();
            while (tr.Peek() != (char)(' ') && tr.Peek() != 13 && tr.Peek() != 10)
            {
                char ch = (char)tr.Read();
                sb.Append(ch);
            }
            value = int.Parse(sb.ToString());
        }
        static void cin(out string value)
        {
            if (tr == null) tr = Console.In;
            StringBuilder sb = new StringBuilder();
            while (tr.Peek() == (char)(' ') || tr.Peek() == 13 || tr.Peek() == 10)
                tr.Read();
            while (tr.Peek() != (char)(' ') && tr.Peek() != 13 && tr.Peek() != 10)
            {
                char ch = (char)tr.Read();
                sb.Append(ch);
            }
            value = sb.ToString();
        }
        static void cin(out double value)
        {
            if (tr == null) tr = Console.In;
            StringBuilder sb = new StringBuilder();
            while (tr.Peek() == (char)(' ') || tr.Peek() == 13 || tr.Peek() == 10)
                tr.Read();
            while (tr.Peek() != (char)(' ') && tr.Peek() != 13 && tr.Peek() != 10)
            {
                char ch = (char)tr.Read();
                if (ch == '.') ch = ',';
                sb.Append(ch);
            }
            value = double.Parse(sb.ToString());
        }
        static void Main(string[] args)
        {
            int r,g,b;
            cin(out r);
            cin(out g);
            cin(out b);
            r = (r + 1) / 2;
            g = (g + 1) / 2;
            b = (b + 1) / 2;
            int a1=(r-1) * 3 + 0;
            int a2 = (g-1) * 3 + 1;
            int a3 = (b-1) * 3 + 2;
            Console.WriteLine( ((new int[] { a1, a2, a3 }).Max()+30).ToString());
        }

    }
}


using System;

namespace CFB_R74_D2
{
    class Program
    {
        static void Main()
        {
            int[] n = ReadInts(3);
            int t = 0;
            if (n[0] > 0)
                t = Math.Max(t, 30 + 3 * ((n[0] - 1) / 2));
            if (n[1] > 0)
                t = Math.Max(t, 31 + 3 * ((n[1] - 1) / 2));
            if (n[2] > 0)
                t = Math.Max(t, 32 + 3 * ((n[2] - 1) / 2));
            Console.WriteLine(t);
        }
        /*****************************************************************************/
        static string[] ReadStr(char sep)
        {
            return ReadStr(new char[] { sep });
        }
        static string[] ReadStr(char[] seps)
        {
            string res = Console.ReadLine();
            if (seps == null) return new string[1] { res };
            else return res.Split(seps);
        }
        static int ReadInt()
        {
            return int.Parse(Console.ReadLine());
        }
        static int[] ReadInts(int n)
        {
            int[] res = new int[n];
            string[] instr = ReadStr(new char[] { ' ' });
            for (int i = 0; i < n; i++)
                res[i] = (i < instr.Length) ? int.Parse(instr[i]) : 0;
            return res;
        }
        static long[] ReadLongs(int n)
        {
            long[] res = new long[n];
            string[] instr = ReadStr(new char[] { ' ' });
            for (int i = 0; i < n; i++)
                res[i] = (i < instr.Length) ? long.Parse(instr[i]) : 0;
            return res;
        }
    }
}


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

namespace Codeforces
{
	class Task90A
	{
		static void Main()
		{
			string[] tokens = Console.In.ReadLine().Split();
			int r = int.Parse(tokens[0]), g = int.Parse(tokens[1]), b = int.Parse(tokens[2]);

			int answer = 0;
			if (r > 0) answer = Math.Max(answer, (r - 1) / 2 * 3 + 30);
			if (g > 1) answer = Math.Max(answer, (g - 1) / 2 * 3 + 31);
			if (b > 2) answer = Math.Max(answer, (b - 1) / 2 * 3 + 32);

			Console.Out.WriteLine(answer);
		}

	}
}


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

namespace ConsoleApp60
{
    class Program
    {
        static void Main(string[] args)
        {
            var N = Console.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)).ToArray();
            var index = -1;
            var j = -1;
            for(int i=0;i<3000;i++)
            {
                j++;
                if (N[j]>=2)
                {
                    N[j] = N[j] - 2;
                }
                else if(N[j]==1)
                {
                    N[j] = N[j] - N[j];
                }
                Console.WriteLine(N[j]);
                index++;
                if(N.Sum()==0)
                {
                    break;
                }
                if (j == 2)
                {
                    j = -1;
                }
            }
           Console.WriteLine(index + 30);
        }
    }
}


using System;

namespace CFB_R74_D2
{
    class Program
    {
        static void Main()
        {
            int[] n = ReadInts(3);
            int t = 30 + 3*(n[0] - 1) / 2;
            t = Math.Max(t, 31 + 3 * (n[1] - 1) / 2);
            t = Math.Max(t, 32 + 3 * (n[2] - 1) / 2);
            Console.WriteLine(t);
        }
        /*****************************************************************************/
        static string[] ReadStr(char sep)
        {
            return ReadStr(new char[] { sep });
        }
        static string[] ReadStr(char[] seps)
        {
            string res = Console.ReadLine();
            if (seps == null) return new string[1] { res };
            else return res.Split(seps);
        }
        static int ReadInt()
        {
            return int.Parse(Console.ReadLine());
        }
        static int[] ReadInts(int n)
        {
            int[] res = new int[n];
            string[] instr = ReadStr(new char[] { ' ' });
            for (int i = 0; i < n; i++)
                res[i] = (i < instr.Length) ? int.Parse(instr[i]) : 0;
            return res;
        }
        static long[] ReadLongs(int n)
        {
            long[] res = new long[n];
            string[] instr = ReadStr(new char[] { ' ' });
            for (int i = 0; i < n; i++)
                res[i] = (i < instr.Length) ? long.Parse(instr[i]) : 0;
            return res;
        }
    }
}


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

namespace Cableway
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ');
            int totalRed = (int.Parse(input[0]) + 1) / 2 - 1;
            int totalGreen = (int.Parse(input[1]) + 1) / 2 - 1;
            int totalBlue = (int.Parse(input[2]) + 1) / 2 - 1;
            int total = 30;
            if (totalBlue > totalGreen && totalBlue > totalRed)
                total += (3 * totalBlue) + 2;
            else if (totalGreen > totalBlue && totalGreen > totalRed)
                total += (3 * totalGreen) + 1;
            else if (totalRed > totalBlue && totalRed > totalGreen)
                total += (3 * totalRed);
            else
                total += (3 * totalBlue) + 2;
            Console.WriteLine(total);
            Console.ReadLine();
        }
    }
}


using System;
class Test {
    static void Main() {
        string [] str = Console.ReadLine().Split();
        int [] a = new int [3];
        bool [] b = new bool [3];
        for(int k=0 ; k<3 ; k++){
            a[k] = int.Parse(str[k]);
        }
        int i = 0;
        int ct = 0;
        while(true){
            if(i==3){
                i=0;
            }
            a[i] -= 2;
            if(a[i]<=0){
                b[i] = true;
            }
            if(b[0] && b[1] && b[2]){
                break;
            }
            ct++;
            i++;
        }
        Console.WriteLine(30+ct);
    }
}


using System;
class Test {
    static void Main() {
        string [] str = Console.ReadLine().Split();
        int i = 0;
        int num = 0;
        int ct = 0;
        while(num<3){
            int tmp = int.Parse(str[i]);
            tmp-=2;
            if(tmp<=0){
                num++;
            }
            if(i==2){
                i=0;
            }
            i++;
            ct++;
        }
        Console.WriteLine(30+ct-1);
    }
}


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

namespace Codeforces
{
    class Program
    {
        static void Main()
        {

            var input = Console.ReadLine().Trim().Split(' ');
            var r = Int32.Parse(input[0]);
            var g = Int32.Parse(input[1]);
            var b = Int32.Parse(input[2]);

            int color = Math.Max(r, Math.Max(g, b));

            int count = 3*(color / 2 + (color % 2) - 1) + 30;

            if (b == color)
            {
                count += 2;
            }
            else if (g == color)
                count += 1;

            Console.WriteLine(count);

        }
    }
}


Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Global
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


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

namespace Cableway
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ');
            int totalRed = (int.Parse(input[0]) + 1) / 2 - 1;
            int totalGreen = (int.Parse(input[1]) + 1) / 2 - 1;
            int totalBlue = (int.Parse(input[2]) + 1) / 2 - 1;
            int total = 30;
            if (totalBlue > totalGreen && totalBlue > totalRed)
                total += (3 * totalBlue) + 2;
            else if (totalGreen > totalBlue && totalGreen > totalRed)
                total += (3 * totalGreen) + 1;
            else if (totalRed > totalBlue && totalRed > totalGreen)
                total += (3 * totalRed);
            else
            {
                int max = Math.Max(totalRed, Math.Max(totalBlue, totalGreen));
                total += (3 * max);
                if (max == totalBlue)
                    total += 2;
                else if (max == totalGreen)
                    total++;
            }
            Console.WriteLine(total);
            Console.ReadLine();
        }
    }
}


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    const int MOD = 1000000007;

    public void Solve()
    {
        int p = ReadInt();
        int k = ReadInt();

        long ans = 1;
        var f = new bool[p];
        for (int i = 1; i < p; i++)
            if (!f[i])
            {
                if (k == 0 && i == 1)
                    continue;
                ans = ans * p % MOD;
                int x = i;
                while (!f[x])
                {
                    f[x] = true;
                    x = x * k % p;
                }
            }

        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("atoms.in");
        //writer = new StreamWriter("atoms.out");
#endif
        try
        {
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
            new Solver().Solve();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
#if DEBUG
#else
            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); }
    private 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; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


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

class TEST{
	static void Main(){
		Sol mySol =new Sol();
		mySol.Solve();
	}
}

class Sol{
	public void Solve(){
		long mod=(long)1e9+7;
		long ans=0;
		if(K==0||K==1){
			ans=1;
			for(int i=0;i<P-1;i++){
				ans*=P;ans%=mod;
			}
			Console.WriteLine(ans);
			return;
		}

		used=new bool[P];
		int cnt=0;
		for(int i=1;i<P;i++){
			if(used[i]==false){
				dfs(i,++cnt);
			}
		}
		//Console.WriteLine(String.Join(" ",used));
		//Console.WriteLine(cnt);

		ans=1;
		for(int i=0;i<cnt;i++){
			ans*=(long)P;
			ans%=mod;
		}
		Console.WriteLine(ans);

	}

	bool[] used;
	void dfs(int now,int cnt){
		used[now]=true;
		int nxt=(int) (((long)now * (long)K)%P);
		if(used[nxt]==false){
			dfs(nxt,cnt);
		}
	}

	int P,K;
	public Sol(){
		var d=ria();
		P=d[0];K=d[1];
	}

	static String rs(){return Console.ReadLine();}
	static int ri(){return int.Parse(Console.ReadLine());}
	static long rl(){return long.Parse(Console.ReadLine());}
	static double rd(){return double.Parse(Console.ReadLine());}
	static String[] rsa(){return Console.ReadLine().Split(' ');}
	static int[] ria(){return Array.ConvertAll(Console.ReadLine().Split(' '),e=>int.Parse(e));}
	static long[] rla(){return Array.ConvertAll(Console.ReadLine().Split(' '),e=>long.Parse(e));}
	static double[] rda(){return Array.ConvertAll(Console.ReadLine().Split(' '),e=>double.Parse(e));}
}


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

class TEST{
	static void Main(){
		Sol mySol =new Sol();
		mySol.Solve();
	}
}

class Sol{
	public void Solve(){
		long mod=(long)1e9+7;
		long ans=0;
		if(K==0){
			ans=1;
			for(int i=0;i<P-1;i++){
				ans*=P;ans%=mod;
			}
			Console.WriteLine(ans);
			return;
		}

		used=new bool[P];
		int cnt=0;
		for(int i=1;i<P;i++){
			if(used[i]==false){
				dfs(i,++cnt);
			}
		}
		//Console.WriteLine(String.Join(" ",used));
		//Console.WriteLine(cnt);

		ans=1;
		for(int i=0;i<cnt;i++){
			ans*=(long)P;
			ans%=mod;
		}
		Console.WriteLine(ans);

	}

	bool[] used;
	void dfs(int now,int cnt){
		used[now]=true;
		int nxt=(int) (((long)now * (long)K)%P);
		if(used[nxt]==false){
			dfs(nxt,cnt);
		}
	}

	int P,K;
	public Sol(){
		var d=ria();
		P=d[0];K=d[1];
	}

	static String rs(){return Console.ReadLine();}
	static int ri(){return int.Parse(Console.ReadLine());}
	static long rl(){return long.Parse(Console.ReadLine());}
	static double rd(){return double.Parse(Console.ReadLine());}
	static String[] rsa(){return Console.ReadLine().Split(' ');}
	static int[] ria(){return Array.ConvertAll(Console.ReadLine().Split(' '),e=>int.Parse(e));}
	static long[] rla(){return Array.ConvertAll(Console.ReadLine().Split(' '),e=>long.Parse(e));}
	static double[] rda(){return Array.ConvertAll(Console.ReadLine().Split(' '),e=>double.Parse(e));}
}


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    const int MOD = 1000000007;

    public void Solve()
    {
        int p = ReadInt();
        int k = ReadInt();

        long ans = 1;
        var f = new bool[p];
        for (int i = 1; i < p; i++)
            if (!f[i])
            {
                ans = ans * p % MOD;
                int x = i;
                while (!f[x])
                {
                    f[x] = true;
                    x = x * k % p;
                }
            }

        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("atoms.in");
        //writer = new StreamWriter("atoms.out");
#endif
        try
        {
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
            new Solver().Solve();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
#if DEBUG
#else
            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); }
    private 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; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


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

namespace Moodular_Arithmetic
{
    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 int[] pa;
        private static int[] size;

        private static int mod = 1000000007;

        private static long Pow(long a, int k)
        {
            long r = 1;
            while (k > 0)
            {
                if ((k & 1) == 1)
                {
                    r = (r*a)%mod;
                }
                a = (a*a)%mod;
                k >>= 1;
            }
            return r;
        }

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

            if (k == 0)
            {
                writer.WriteLine(Pow(p, p - 1));
                writer.Flush();
                return;
            }

            pa = new int[p];
            size = new int[p];

            for (int i = 0; i < pa.Length; i++)
            {
                pa[i] = i;
                size[i] = 1;
            }

            for (int i = 1; i < p; i++)
            {
                int pi = GP(i);
                int kpi = GP((int) ((k*i)%p));

                if (pi != kpi)
                {
                    pa[pi] = kpi;
                    size[kpi] += size[pi];
                }
            }

            var d = new Dictionary<int, int>();
            for (int i = 1; i < p; i++)
            {
                if (pa[i] == i)
                {
                    if (d.ContainsKey(size[i]))
                        d[size[i]] = 1 + d[size[i]];
                    else
                    {
                        d[size[i]] = 1;
                    }
                }
            }

            long count = 1;

            foreach (var dd in d)
            {
                count = (count*Pow(dd.Key*dd.Value + 1, dd.Value))%mod;
            }

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

        private static int GP(int i)
        {
            if (pa[i] == i)
                return i;
            return pa[i] = GP(pa[i]);
        }

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


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

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

        static long mod = 1000000007;
        public static long Pow(long a, long n)
        {
            long res = 1L;
            while (n > 0)
            {
                if ((n & 1) != 0)
                    res = (res * a) % mod;
                a = (a * a) % mod;
                n >>= 1;
            }
            return res;
        }

        private void Go()
        {
            long p = GetInt();
            long k = GetInt();

            if (k == 0)
            {
                Wl(Pow(p, p - 1));
            }
            else if (k == 1)
            {
                Wl(Pow(p, p));
            }
            else
            {
                long x = k;
                long kp = 1;
                while (x != 1)
                {
                    x *= k;
                    x %= p;
                    kp++;
                }

                Wl(Pow(p, (p - 1) / kp));
            }
        }

        #region Template

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

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

            return ioEnum.Current;
        }

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

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

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

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

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

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

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

        #endregion
    }
}


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

namespace Moodular_Arithmetic
{
    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 int[] pa;
        private static int[] size;

        private static int mod = 1000000007;

        private static long Pow(long a, int k)
        {
            long r = 1;
            while (k > 0)
            {
                if ((k & 1) == 1)
                {
                    r = (r*a)%mod;
                }
                a = (a*a)%mod;
                k >>= 1;
            }
            return r;
        }

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

            if (k == 0)
            {
                writer.WriteLine(Pow(p, p - 1));
                writer.Flush();
                return;
            }
            if (k == 1)
            {
                writer.WriteLine(Pow(p, p));
                writer.Flush();
                return;
            }

            pa = new int[p];
            size = new int[p];

            for (int i = 0; i < pa.Length; i++)
            {
                pa[i] = i;
                size[i] = 1;
            }

            for (int i = 1; i < p; i++)
            {
                int pi = GP(i);
                int kpi = GP((int) ((k*i)%p));

                if (pi != kpi)
                {
                    pa[pi] = kpi;
                    size[kpi] += size[pi];
                }
            }

            var d = new Dictionary<int, int>();
            for (int i = 1; i < p; i++)
            {
                if (pa[i] == i)
                {
                    if (d.ContainsKey(size[i]))
                        d[size[i]] = 1 + d[size[i]];
                    else
                    {
                        d[size[i]] = 1;
                    }
                }
            }

            long count = 1;

            foreach (var dd in d)
            {
                count = (count*Pow(dd.Key*dd.Value + 1, dd.Value))%mod;
            }

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

        private static int GP(int i)
        {
            if (pa[i] == i)
                return i;
            return pa[i] = GP(pa[i]);
        }

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


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    const int MOD = 1000000007;

    public void Solve()
    {
        int p = ReadInt();
        int k = ReadInt();

        long ans = 1;
        var f = new bool[p];
        for (int i = 1; i < p; i++)
            if (!f[i])
            {
                ans = ans * p % MOD;
                int x = i;
                while (!f[x])
                {
                    f[x] = true;
                    x = (int)(1L * x * k % p);
                }
            }
        if (k == 1)
            ans = ans * p % MOD;

        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("atoms.in");
        //writer = new StreamWriter("atoms.out");
#endif
        try
        {
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
            new Solver().Solve();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
#if DEBUG
#else
            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); }
    private 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; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    const int MOD = 1000000007;

    int Fun(int n, int c, int[] a, int k)
    {
        if (c == n)
        {
            for (int i = 0; i < n; i++)
                if (a[k * i % n] != k * a[i] % n)
                    return 0;
            return 1;
        }
        int ret = 0;
        for (int i = 0; i < n; i++)
        {
            a[c] = i;
            ret += Fun(n, c + 1, a, k);
        }
        return ret;
    }

    public void Solve()
    {
        int p = ReadInt();
        int k = ReadInt();

        long ans = 1;
        var f = new bool[p];
        for (int i = 1; i < p; i++)
            if (!f[i])
            {
                ans = ans * p % MOD;
                int x = i;
                while (!f[x])
                {
                    f[x] = true;
                    x = x * k % p;
                }
            }
        if (k == 1)
            ans = ans * p % MOD;

        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("atoms.in");
        //writer = new StreamWriter("atoms.out");
#endif
        try
        {
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
            new Solver().Solve();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
#if DEBUG
#else
            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); }
    private 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; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


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

namespace TaskB
{
    class Program
    {
        class Scanner
        {
            string[] s;
            int i;

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

            public Scanner()
            {
                //s = @"6 16".Split(cs, StringSplitOptions.RemoveEmptyEntries);
                s = new string[0];
                i = 0;
            }

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

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

            public long nextLong()
            {
                return long.Parse(next());
            }
        }
        private static Dictionary<int, long> magic = new Dictionary<int, long>();
        static void Main(string[] args)
        {

            Scanner sc = new Scanner();
            int n = sc.nextInt();
            long m = sc.nextInt();

            var order = Enumerable.Range(1, n).Select(h => h.ToString()).OrderBy(h => h).Select(jj => int.Parse(jj)).ToList();
            var natural = Enumerable.Range(1, n).ToList();
            int orderi = 0;
            magic[1] = 1;
            for (int i = 2; i <= n; i++)
            {
                magic[i] = magic[i - 1]*2;
            }

            int[] arr = new int[n];
            int currStart = 0;
            int currEnd = n - 1;
            long magicNumber = (long)Math.Pow(2, n - 2);
            int ii = 1;
            while (ii <= n)
            {
                //long currentM = m;
                //for (int k = 0; k < order.Count; k++)
                //{
                //    if (currentM > magicNumber/magic[order[k]])
                //    {
                //        currentM -= magicNumber/magic[order[k]];
                //        continue;
                //    }
                //    arr[i-1] = order[k];
                //    order.RemoveAt(k);

                //}
                //

                //while (currentM > magicNumber/magic[num])
                //{
                //    currentM
                //}
                int num = order.First();
                if (m <= magicNumber / magic[num])
                {
                    arr[currStart] = num;
                    currStart++;
                    order.Remove(num);
                    if (natural.First() != num)
                    {
                        int num2 = natural.First();
                        //m -= magicNumber / magic[num2];
                        arr[currEnd] = num2;
                        currEnd--;
                        order.Remove(num2);
                        natural.Remove(num2);
                        ii++;
                    }
                    natural.Remove(num);
                }
                else
                {
                    num = natural.First();
                    m -= magicNumber / magic[num];
                    arr[currEnd] = num;
                    currEnd--;
                    order.Remove(num);
                    natural.Remove(num);
                }
                ii++;
            }
            PrintArr(arr);
        }

        private static void PrintArr(int[] arr)
        {
            StringBuilder sb = new StringBuilder(arr.Length * 2 - 1);
            for (int i = 0; i < arr.Length; i++)
            {
                sb.Append(arr[i]);
                if (i != arr.Length - 1)
                {
                    sb.Append(" ");
                }

            }
            Console.WriteLine(sb);
        }

    }
}


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

namespace TaskB
{
    class Program
    {
        class Scanner
        {
            string[] s;
            int i;

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

            public Scanner()
            {
                //s = @"6 3".Split(cs, StringSplitOptions.RemoveEmptyEntries);
                s = new string[0];
                i = 0;
            }

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

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

            public long nextLong()
            {
                return long.Parse(next());
            }
        }
        static void Main(string[] args)
        {
            Scanner sc = new Scanner();
            int n = sc.nextInt();
            long m = sc.nextInt();

            int[] arr = new int[n];
            int currStart = 0;
            int currEnd = n - 1;
            long magicNumber = (long)Math.Pow(2, n - 2);
            for (int i = 1; i <= n; i++)
            {
                if (m <= magicNumber)
                {
                    arr[currStart] = i;
                    currStart++;
                }
                else
                {
                    m -= magicNumber;
                    arr[currEnd] = i;
                    currEnd--;
                }
                magicNumber /= 2;
            }
            PrintArr(arr);
        }

        private static void PrintArr(int[] arr)
        {
            StringBuilder sb = new StringBuilder(arr.Length * 2 - 1);
            for (int i = 0; i < arr.Length; i++)
            {
                sb.Append(arr[i]);
                if (i != arr.Length - 1)
                {
                    sb.Append(" ");
                }

            }
            Console.WriteLine(sb);
        }

    }
}


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

namespace prB2 {

    class Program {
#if ONLINE_JUDGE
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), System.Text.Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), System.Text.Encoding.ASCII, 1024 * 10);
#else
        private static readonly StreamWriter writer = new StreamWriter("output");
        private static readonly StreamReader reader = new StreamReader("input");
#endif
        static void Main(string[] args) {
            string[] ss = reader.ReadLine().Split(' ');
            int n = int.Parse(ss[0]);
            ulong m = ulong.Parse(ss[1]);
            ulong[] st = new ulong[46];
            st[0] = 1;
            for(int i = 1; i < 46; i++) {
                st[i] = st[i - 1] * 2;
            }
            int q = 1;
            HashSet<int> set = new HashSet<int>();
            for(int i = 0; i < n; i++) {
                ulong p = 0;
                while(q < n && m > p + st[n - 1 - q]) {
                    p += st[n - 1 - q];
                    q++;
                }
                writer.Write(q);
                writer.Write(' ');
                set.Add(q);
                m -= p;
                q++;
                if(q >= n)
                    break;
            }
            for(int i = n; i >= 1; i--) {
                if(!set.Contains(i)) {
                    writer.Write(i);
                    writer.Write(' ');
                }
            }
            writer.Flush();
#if !ONLINE_JUDGE
            writer.Close();
#endif
        }
        private static int Next() {
            int c;
            int res = 0;
            do {
                c = reader.Read();
                if(c == -1)
                    return res;
            } while(c != '-' && (c < '0' || c > '9'));
            int sign = 1;
            if(c == '-') {
                sign = -1;
                c = reader.Read();
            }
            res = c - '0';
            while(true) {
                c = reader.Read();
                if(c < '0' || c > '9')
                    return res * sign;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


using System;

namespace Permutations
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            var strs = str.Split(' '); // Divide a string de entrada
            int n = 0;
            long m = 0;
            int.TryParse(strs[0], out n); // Tenta converter a entrada na posição 0
            long.TryParse(strs[1], out m); // Tenta converter a entrada na posição 1
            --m;

            int[] array = new int[n];

            var tempm = m;
            for (int i = 0; i < n; i++)
            {
                array[i] = (int)(tempm % 2); // Preenche o array com o resoltado de tempm % 2 (resto)
                tempm /= 2; // Divide tempm por 2
            }

            perm(array, 1, n); // Resolve

            Console.Write(n); // Imprime n
            Console.Write(" "); // Espaço requisitado no output

            perm(array, 2, n); // Resolve

            Console.WriteLine("");
        }

        static void perm(int[] array, int variation, int n)
        {
            for (int i = n - variation; i >= 0; i--)
            {
                if (!(array[n - 1 - i - 1] == 0)) // Se o array na posição n - 1 - i -1 não for igual a 0
                {
                    Console.Write(i + 1); // Imprime valor de i + 1
                    Console.Write(" "); // Espaço requisitado no output
                }
            }
        }
    }
}


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

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

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

            long[] ans = new long[n];
            long start = 0;
            long end = n - 1;
            long comp = 1L << (n - 2);

            for (int i = 1; i <= n; i++)
            {
                if (m > comp)
                {
                    m -= comp;
                    ans[end--] = i;
                }
                else
                {
                    ans[start++] = i;
                }
                comp >>= 1;
            }

            Wl(string.Join(" ", ans));
        }

        #region Template

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

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

            return ioEnum.Current;
        }

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

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

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

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

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

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

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

        #endregion
    }
}


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

namespace TaskB
{
    class Program
    {
        class Scanner
        {
            string[] s;
            int i;

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

            public Scanner()
            {
                //s = @"6 3".Split(cs, StringSplitOptions.RemoveEmptyEntries);
                s = new string[0];
                i = 0;
            }

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

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

            public long nextLong()
            {
                return long.Parse(next());
            }
        }
        static void Main(string[] args)
        {
            Scanner sc = new Scanner();
            int n = sc.nextInt();
            long m = sc.nextLong();

            int[] arr = new int[n];
            int currStart = 0;
            int currEnd = n - 1;
            long magicNumber = (long)Math.Pow(2, n - 2);
            for (int i = 1; i <= n; i++)
            {
                if (m <= magicNumber)
                {
                    arr[currStart] = i;
                    currStart++;
                }
                else
                {
                    m -= magicNumber;
                    arr[currEnd] = i;
                    currEnd--;
                }
                magicNumber /= 2;
            }
            PrintArr(arr);
        }

        private static void PrintArr(int[] arr)
        {
            StringBuilder sb = new StringBuilder(arr.Length * 2 - 1);
            for (int i = 0; i < arr.Length; i++)
            {
                sb.Append(arr[i]);
                if (i != arr.Length - 1)
                {
                    sb.Append(" ");
                }

            }
            Console.WriteLine(sb);
        }

    }
}


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

namespace CodeForcesPractice
{
    class CF513B2
    {
        private static int n;
        private static long m;

        private static void Execute(string[] args)
        {
            var input = args.Select(s => Int64.Parse(s)).ToList();

            n = (int)input[0];
            m = input[1];

            var maxFpCount = (long)Math.Pow(2, n - 1);

            var p = Enumerable.Repeat(0, n).ToList();

            xx(p, 1,0,n-1,m-1,0,maxFpCount);

            foreach (var i in p)
            {
                Console.Write(i + " ");
            }
        }

        private static void xx(List<int> p, int i, int imin, int imax, long m, long min, long max)
        {
            if (i > n)
            {
                return;
            }

            var midpoint = (max - min)/2 + min;

            if (m < midpoint)
            {
                p[imin] = i;
                xx(p, i+1,imin+1, imax,m,min,midpoint);
            }
            else
            {
                p[imax] = i;
                xx(p, i + 1, imin, imax-1, m, midpoint, max);
            }
        }

        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ');
            Execute(input);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Collections;
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 Int64 ReadNextInt64()
        {
            return Int64.Parse(ReadNextToken());
        }

        public double ReadNextDouble()
        {
            return double.Parse(ReadNextToken());
        }

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

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

        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;

        int n;
        Int64 m;

        int[] position;
        bool[] InFront;

        public void Print(int i)
        {
            if (i > n)
                return;

            if (InFront[i])
            {
                Console.Write(i + " ");
                Print(i + 1);
            }
            else
            {
                Print(i + 1);
                Console.Write(i + " ");
            }
        }

        public void Solve()
        {
            n = ioHelper.ReadNextInt();
            m = ioHelper.ReadNextInt64();
            position = new int[n + 1];
            InFront = new bool[n + 1];
            int i;
            for (i = 1; i < n; i++)
            {
                Int64 withMeInFront = (Int64)Math.Pow(2, n - i - 1);
                if (m > withMeInFront)
                {
                    m -= withMeInFront;
                    InFront[i] = false;
                }
                else
                {
                    InFront[i] = true;
                }
            }

            Print(1);
            Console.WriteLine("");
        }

        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.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rocketon_2015
{
    class B
    {
        static string[] input;
        static int n;
        static int m;
        static List<int> items = new List<int>();
        static int top = 0;
        static List<List<int>> vals = new List<List<int>>();

        static void Main(string[] args)
        {
            input = Console.ReadLine().Split(' ');
            n = int.Parse(input[0]);
            m = int.Parse(input[1]);

            for (int i = 1; i <= n; i++)
            {
                items.Add(i);
            }

            GeneratePermutations(items.ToList());

            Console.WriteLine(string.Join(" ", vals[m - 1].ToArray()));
        }

        static void GeneratePermutations(List<int> items)
        {
            int[] current_permutation = new int[items.Count];

            bool[] in_selection = new bool[items.Count];

            PermuteItems(items, in_selection,
                current_permutation, 0);
        }

        static void PermuteItems(List<int> items, bool[] in_selection, int[] current_permutation, int next_position)
        {
            if (next_position == items.Count)
            {
                int value = f(current_permutation);
                if (value > top)
                {
                    top = value;
                    vals = new List<List<int>>();
                }
                if (value == top)
                {
                    vals.Add((current_permutation as int[]).ToList());
                }
            }
            else
            {
                for (int i = 0; i < items.Count; i++)
                {
                    if (!in_selection[i])
                    {
                        in_selection[i] = true;
                        current_permutation[next_position] = items[i];

                        PermuteItems(items, in_selection, current_permutation, next_position + 1);

                        in_selection[i] = false;
                    }
                }
            }
        }

        static int f(int[] p)
        {
            int res = 0;

            for (int i = 0; i < n; i++)
            {
                for (int j = i; j < n; j++)
                {
                    int min = 100;
                    for (int k = i; k <= j; k++)
                    {
                        if (int.Parse(p[k].ToString()) < min)
                        {
                            min = int.Parse(p[k].ToString());
                        }
                    }
                    res += min;
                }
            }

            return res;
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using Kattis.IO;
using System.Resources;

public class _513B {

    static List<int> calc (List<int> cand, long m) {
        int first = cand [0];
        List<int> res = new List<int> ();
        if (cand.Count == 1) {
            res.Add (first);
            return res;
        }

        long half = 1L << (cand.Count - 2);
        cand.RemoveAt (0);
        if (m <= half) {
            res = calc (cand, m);
            res.Insert (0, first);
        } else {
            res = calc (cand, m - half);
            res.Add (first);
        }
        return res;
    }

    public static void Main (string[] args) {

        var cin = new Tokenizer(Console.OpenStandardInput());
        var cout = new BufferedStdoutWriter ();

        int n = int.Parse (cin.Next ());
        long m = long.Parse (cin.Next ());
        List<int> cand = new List<int> ();
        for (int i = 1; i <= n; i++)
            cand.Add (i);
        List<int> res = calc (cand, m);
        cout.Write ("{0}", res [0]);
        for (int i = 1; i < res.Count; i++)
            cout.Write (" {0}", res [i]);
        cout.WriteLine ();

        cout.Close ();
    }
}

namespace Kattis.IO {
    public class NoMoreTokensException : Exception {
    }

    public class Tokenizer {
        string[] tokens = new string[0];
        private int pos;
        StreamReader reader;

        public Tokenizer (Stream inStream) {
            var bs = new BufferedStream (inStream);
            reader = new StreamReader (bs);
        }

        public Tokenizer () : this (Console.OpenStandardInput ()) {
            // Nothing more to do
        }

        private string PeekNext () {
            if (pos < 0)
                // pos < 0 indicates that there are no more tokens
                return null;
            if (pos < tokens.Length) {
                if (tokens [pos].Length == 0) {
                    ++pos;
                    return PeekNext ();
                }
                return tokens [pos];
            }
            string line = reader.ReadLine ();
            if (line == null) {
                // There is no more data to read
                pos = -1;
                return null;
            }
            // Split the line that was read on white space characters
            tokens = line.Split (null);
            pos = 0;
            return PeekNext ();
        }

        public bool HasNext () {
            return (PeekNext () != null);
        }

        public string Next () {
            string next = PeekNext ();
            if (next == null)
                throw new NoMoreTokensException ();
            ++pos;
            return next;
        }
    }

    public class Scanner : Tokenizer {

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

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

        public float NextFloat () {
            return float.Parse (Next ());
        }

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

    public class BufferedStdoutWriter : StreamWriter {
        public BufferedStdoutWriter () : base (new BufferedStream (Console.OpenStandardOutput ())) {
        }
    }
}


using System;

namespace Permutations
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            var strs = str.Split(' '); // Divide a string de entrada
            int n = 0;
            long m = 0;
            int.TryParse(strs[0], out n); // Tenta converter a entrada na posição 0
            long.TryParse(strs[1], out m); // Tenta converter a entrada na posição 1
            --m;

            int[] array = new int[n];

            var tempm = m;
            for (int i = 0; i < n; i++)
            {
                array[i] = (int)(tempm % 2); // Preenche o array com o resoltado de tempm % 2 (resto)
                tempm /= 2; // Divide tempm por 2
            }

            perm(array, n, 1); // Resolve

            Console.Write(n); // Imprime n
            Console.Write(" "); // Espaço requisitado no output

            perm(array, n, 2); // Resolve

            Console.WriteLine("");
        }

        static void perm(int[] array, int n, int variation = 1)
        {
            if (variation == 1) {
                for (int i = 0; i < n - 1; i ++)
                {
                    if (array[n - 1 - i - 1] == 0) // Se o array na posição n - 1 - i -1 não for igual a 0
                    {
                        Console.Write(i + 1); // Imprime valor de i + 1
                        Console.Write(" "); // Espaço requisitado no output
                    }

                }
            } else if (variation == 2) {
                for (int i = n - 2; i >= 0; i--)
                {
                    if (!(array[n - 1 - i -1] == 0)) // Se o array na posição n - 1 - i -1 não for igual a 0
                    {
                        Console.Write(i + 1); // Imprime valor de i + 1
                        Console.Write(" "); // Espaço requisitado no output
                    }

                }
            } else {
                Environment.Exit(0);
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;

namespace CodeForcesPractice
{
    class CF513B1
    {
        private static int n;
        private static int m;

        private static void Execute(string[] args)
        {
            var input = args.Select(s => Int32.Parse(s)).ToList();

            n = input[0];
            m = input[1];

            var allPermutations = Permutations(Enumerable.Range(1, n).ToList());
            var maxFp = allPermutations.Max(p => F(p));
            var result = allPermutations.Where(p => F(p) == maxFp).Skip(m - 1).First();

            foreach (var i in result)
            {
                Console.Write(i + " ");
            }
        }

        private static IEnumerable<List<int>> Permutations(List<int> elements)
        {
            if (elements.Count == 1)
            {
                yield return elements;
                yield break;
            }

            for (int i = 0; i < elements.Count; i++)
            {
                var ex = elements.Except(new[] {elements[i]}).ToList();

                foreach (var p in Permutations(ex))
                {
                    p.Insert(0,elements[i]);
                    yield return p;
                }
            }
        }

        private static int F(List<int> p)
        {
            int sum = 0;

            for (int i = 0; i < n; i++)
            {
                for (int j = i; j < n; j++)
                {
                    sum += min(p, i, j);
                }
            }

            return sum;
        }

        private static int min(List<int> p, int i, int j)
        {
            int min = p[i];

            for (int x = i+1; x <= j; x++)
            {
                if (p[x] < min)
                {
                    min = p[x];
                }
            }

            return min;
        }

        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ');
            Execute(input);
        }
    }
}


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

namespace ConsoleApplication15
{
    class Program
    {
        static int Main(string[] args)
        {
            string[] inArr = Console.ReadLine().Split(' ');
            int n = int.Parse(inArr[0]),
                m = int.Parse(inArr[1]);
            int[] originalArr = new int[n];
            for (int i = 0; i < n; i++)
                originalArr[i] = i + 1;
            string[] allArrays= new string[factorial(n)];
            for (int i=0; i<factorial(n); i++)
            {
                allArrays[i] = getNumbers(originalArr, i);
            }
            int[] allFp = new int[allArrays.Length];
            int maxFp = 0;
            for (int cur = 0; cur < allArrays.Length; cur++)
            {
                int fP = 0;
                string[] p = allArrays[cur].Split(' ');
                for (int i = 0; i < n; i++)
                {
                    for (int j = i; j < n; j++)
                    {
                        int min = int.Parse(p[i]);
                        for (int x = i; x <= j; x++)
                        {
                            if (int.Parse(p[x]) < min)
                                min = int.Parse(p[x]);
                        }
                        fP += min;
                    }
                }
                allFp[cur] = fP;
                if (fP > maxFp) maxFp = fP;
            }
            int curM = 1;
            for (int i = 0; i < allArrays.Length; i++)
            {
                if (allFp[i] == maxFp)
                {

                    if (curM == m)
                    {
                        Console.Write(allArrays[i]);
                        break;
                    }
                    curM++;
                }
            }
            return 0;
        }
        static string getNumbers(int[] nums, long cur)
        {

            int size = nums.Length;
            if (size == 1) return Convert.ToString(nums[0]);
            long amount = factorial(size);
            long ind = (long)(cur / (amount / size));
            int[] newNums = new int[size - 1];
            int Tx = 0;
            for (int x = 0; x < size; x++)
            {
                if (x == ind)
                    continue;
                newNums[Tx] = nums[x];
                Tx++;
            }
            return nums[ind] + " " + getNumbers(newNums, (cur - (amount / size) * ind));

        }
        static long factorial(int n)
        {
            return n <= 1 ? 1 : n * factorial(n - 1);
        }
    }
}


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

namespace RocketB
{
    class Program
    {

        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            var strs = str.Split(' ');
            int n = 0;
            long m = 0;
            int.TryParse(strs[0], out n);
            long.TryParse(strs[1], out m);
            --m;

            int[] array = new int[n];

            var tempm = m;
            for (int i = 0; i < n; i++)
            {
                array[i] = (int)(tempm % 2);
                tempm /= 2;
            }

            for (int i = 0; i < n - 1; i ++)
            {
                if (array[n - 1 - i - 1] == 0)
                {
                    Console.Write(i + 1);
                    Console.Write(" ");
                }
                else
                {
                    //Console.Write(i + 1 );
                    //Console.Write(" ");
                }

            }

           // if (p2 > 0)
            {
                Console.Write(n - 1 + 1 );
                Console.Write(" ");
            }

            for (int i = n - 2; i >= 0; i--)
            {
                if (array[n - 1 - i -1] == 0)
                {
                    //Console.Write(i + 1);
                    //Console.Write(" ");
                }
                else
                {
                    Console.Write(i + 1);
                    Console.Write(" ");
                }

            }
            Console.WriteLine("");

        }
    }
}


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

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

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

            long[] ans = new long[n];
            long start = 0;
            long end = n - 1;
            long comp = 1L << (n - 2);

            for (int i = 1; i <= n; i++)
            {
                if (m > comp)
                {
                    m -= comp;
                    ans[end--] = i;
                }
                else
                {
                    ans[start++] = i;
                }
                comp >>= 1;
            }

            Wl(string.Join(" ", ans));
        }

        #region Template

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

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

            return ioEnum.Current;
        }

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

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

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

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

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

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

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

        #endregion
    }
}


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

namespace RocketB
{
    class Program
    {

        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            var strs = str.Split(' ');
            int n = 0;
            int m = 0;
            int.TryParse(strs[0], out n);
            int.TryParse(strs[1], out m);
            --m;

            int[] array = new int[n];

            var tempm = m;
            for (int i = 0; i < n; i++)
            {
                array[i] = tempm % 2;
                tempm /= 2;
            }

            for (int i = 0; i < n - 1; i ++)
            {
                if (array[n - 1 - i - 1] == 0)
                {
                    Console.Write(i + 1);
                    Console.Write(" ");
                }
                else
                {
                    //Console.Write(i + 1 );
                    //Console.Write(" ");
                }

            }

           // if (p2 > 0)
            {
                Console.Write(n - 1 + 1 );
                Console.Write(" ");
            }

            for (int i = n - 2; i >= 0; i--)
            {
                if (array[n - 1 - i -1] == 0)
                {
                    //Console.Write(i + 1);
                    //Console.Write(" ");
                }
                else
                {
                    Console.Write(i + 1);
                    Console.Write(" ");
                }

            }
            Console.WriteLine("");

        }
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Numerics;
class Program
{
    static void Main()
    {
        long n, m, i;
        long[] u = new long[64];
        var s = Console.ReadLine().Split().Select(long.Parse).ToArray();
        n = s[0]; m = s[1];
        m--;
        for (i = n; --i != 0; )
            if ((m & (1L << (int)i - 1)) == 0)
            {
                Console.Write((n - i) + " ");
                u[n - i] = 1;
            }
        for (; n != 0; n--) if (u[n] == 0) Console.Write(n + " ");
    }
}


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

// (づ°ω°)づﾐ★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    public void Solve()
    {
        int n = ReadInt();
        long m = ReadLong() - 1;
        int l = 0, r = n - 1;
        var a = new int[n];
        for (int i = n - 2, j = 1; i >= 0; i--, j++)
        {
            if ((m >> i & 1) == 1)
                a[r--] = j;
            else
                a[l++] = j;
        }
        a[l] = n;
        WriteArray(a);
    }

    #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("game.in");
        //writer = new StreamWriter("game.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);
    }

    #endregion
}