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

using E = System.Linq.Enumerable;
using System.Threading;
using System.Numerics;

internal partial class Solver {
    public void Run() {
        var m = nl();
        var x = nl();

        cout.WriteLine(Solve(m, x));
    }

    /*
    Sample 1
    0 -> 0
    1 -> 3 -> 1 -> 3
    2 -> 2 -> 2 -> 2 (2*3^x%4 --> 3^x%2 と等化)
    3 -> 1 -> 3 -> 1

    g = gcd(start, M) ごとに場合分けすればよい
    start' = start / g
    M' = M / g
    start, start * x, ... start * x^k % M ->
    (start/g), start, ... start * x^k % M')
    start', start' * x, ... start' * x^k % M'

     * */

    public List<long> Factorize(long x) {
        var res = new List<long>();
        for (long i = 2; i * i <= x; i++) {
            if (x % i == 0) {
                res.Add(i);
                while (x % i == 0) x /= i;
            }
        }
        if (x != 1) res.Add(x);
        return res;
    }

    private long Solve(long m, long x) {
        // from i to (i*x)%m
        long ans = 0;
        // x^phi(m) = 1 (mod m)
        var primes = Factorize(m);
        var len = primes.Count;
        for (int i = 0; i < len; i++) {
            primes.AddRange(Factorize(primes[i] - 1));
        }
        primes.Sort();
        primes = primes.Distinct().ToList();

        foreach (var g in Divisors(m)) {
            var m2 = m / g;
            var phi = Phi(m2);
            long minPower = phi;
            foreach (var p in primes) {
                if (p > minPower) break;
                if (minPower % p == 0) {
                    int cnt = 0;
                    while (minPower % p == 0) {
                        minPower /= p;
                        cnt++;
                    }
                    for (int i = 0; i < cnt; i++) {
                        if (BigInteger.ModPow(x, minPower, m2) == 1) break;
                        minPower *= p;
                    }
                }
            }

            ans += phi / minPower;
        }
        return ans;
    }

    public static long ModPow(long x, long n, long mod) {
        long t = x, ret = 1;
        while (n > 0) {
            if ((n & 1) != 0) {
                ret = (long)(((decimal)t * ret) % mod);
            }
            t = (long)((decimal)t * t % mod);
            n >>= 1;
        }
        return ret;
    }

    public static long Phi(long n) {
        long phi = n;

        for (long i = 2; i * i <= n && i < n; i++) {
            if (n % i == 0) {
                while (n % i == 0) {
                    n /= i;
                }

                phi = phi / i * (i - 1);
            }
        }
        if (n > 1) {
            phi = phi / n * (n - 1);
        }

        return phi;
    }

    Dictionary<long, List<long>> cache = new Dictionary<long, List<long>>();

    public List<long> Divisors(PrimeSet primes, long x) {
        //if (cache.TryGetValue(x, out var res)) return res;
        var ret = new List<long> { 1 };
        foreach (var p in primes) {
            if (p * p > x) break;
            int last = 0;
            while (x % p == 0) {
                int count = ret.Count;
                for (int i = last; i < count; i++) {
                    ret.Add(ret[i] * p);
                }
                last = count;
                x /= p;
            }
        }
        if (x != 1) {
            int count = ret.Count;
            for (int i = 0; i < count; i++) {
                ret.Add(ret[i] * x);
            }
        }
        cache[x] = ret;
        return ret;
    }

    public List<long> Divisors(long x) {
        if (cache.TryGetValue(x, out var res)) return res;
        var ret = new List<long>();
        for (long i = 1; i * i <= x; i++) {
            if (x % i == 0) {
                ret.Add(i);
                if (i != x / i) {
                    ret.Add(x / i);
                }
            }
        }
        ret.Sort();
        cache[x] = ret;
        return ret;
    }

}

public class PrimeSet : List<int> {
    private readonly bool[] isPrime;

    public PrimeSet(int size)
        : base() {
        isPrime = Enumerable.Repeat(true, size).ToArray();
        Add(2);
        for (int i = 3; i <= size; i += 2) {
            if (!isPrime[i >> 1]) {
                continue;
            }

            Add(i);
            for (long j = (long)i * i; j <= size; j += i + i) {
                isPrime[j >> 1] = false;
            }
        }
    }

    public bool IsPrime(long x) {
        if (x == 2) {
            return true;
        }

        if (x <= 1 || x % 2 == 0) {
            return false;
        }

        return isPrime[x >> 1];
    }
}

// PREWRITEN CODE BEGINS FROM HERE

static public class StringExtensions {
    static public string JoinToString<T>(this IEnumerable<T> source, string separator = " ") {
        return string.Join(separator, source);
    }
}

internal partial class Solver : Scanner {
    static readonly int? StackSizeInMebiByte = null; //50;
    public static void StartAndJoin(Action action, int maxStackSize) {
        var thread = new Thread(new ThreadStart(action), maxStackSize);
        thread.Start();
        thread.Join();
    }

    public static void Main() {
#if LOCAL
        byte[] inputBuffer = new byte[1000000];
        var inputStream = Console.OpenStandardInput(inputBuffer.Length);
        using (var reader = new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length)) {
            Console.SetIn(reader);
            new Solver(Console.In, Console.Out).Run();
        }
#else
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        if (StackSizeInMebiByte.HasValue) {
            StartAndJoin(() => new Solver(Console.In, Console.Out).Run(), StackSizeInMebiByte.Value * 1024 * 1024);
        } else {
            new Solver(Console.In, Console.Out).Run();
        }
        Console.Out.Flush();
#endif
    }

#pragma warning disable IDE0052
    private readonly TextReader cin;
    private readonly TextWriter cout;
    private readonly TextWriter cerr;
#pragma warning restore IDE0052

    public Solver(TextReader reader, TextWriter writer)
        : base(reader) {
        cin = reader;
        cout = writer;
        cerr = Console.Error;
    }

    public Solver(string input, TextWriter writer)
        : this(new StringReader(input), writer) {
    }

#pragma warning disable IDE1006
#pragma warning disable IDE0051
    private int ni() { return NextInt(); }
    private int[] ni(int n) { return NextIntArray(n); }
    private long nl() { return NextLong(); }
    private long[] nl(int n) { return NextLongArray(n); }
    private double nd() { return NextDouble(); }
    private double[] nd(int n) { return NextDoubleArray(n); }
    private string ns() { return Next(); }
    private string[] ns(int n) { return NextArray(n); }
#pragma warning restore IDE1006
#pragma warning restore IDE0051
}

#if DEBUG
internal static class LinqPadExtension {
    public static string TextDump<T>(this T obj) {
        if (obj is IEnumerable) return (obj as IEnumerable).Cast<object>().JoinToString().Dump();
        else return obj.ToString().Dump();
    }
    public static T Dump<T>(this T obj) {
        return LINQPad.Extensions.Dump(obj);
    }
}
#endif

public class Scanner {
    private readonly TextReader Reader;
    private readonly CultureInfo ci = CultureInfo.InvariantCulture;

    private readonly char[] buffer = new char[2 * 1024];
    private int cursor = 0, length = 0;
    private string Token;
    private readonly StringBuilder sb = new StringBuilder(1024);

    public Scanner()
        : this(Console.In) {
    }

    public Scanner(TextReader reader) {
        Reader = reader;
    }

    public int NextInt() { return checked((int)NextLong()); }
    public long NextLong() {
        var s = Next();
        long r = 0;
        int i = 0;
        bool negative = false;
        if (s[i] == '-') {
            negative = true;
            i++;
        }
        for (; i < s.Length; i++) {
            r = r * 10 + (s[i] - '0');
#if DEBUG
            if (!char.IsDigit(s[i])) throw new FormatException();
#endif
        }
        return negative ? -r : r;
    }
    public double NextDouble() { return double.Parse(Next(), ci); }
    public string[] NextArray(int size) {
        string[] array = new string[size];
        for (int i = 0; i < size; i++) {
            array[i] = Next();
        }

        return array;
    }
    public int[] NextIntArray(int size) {
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextInt();
        }

        return array;
    }

    public long[] NextLongArray(int size) {
        long[] array = new long[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextLong();
        }

        return array;
    }

    public double[] NextDoubleArray(int size) {
        double[] array = new double[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextDouble();
        }

        return array;
    }

    public string Next() {
        if (Token == null) {
            if (!StockToken()) {
                throw new Exception();
            }
        }
        var token = Token;
        Token = null;
        return token;
    }

    public bool HasNext() {
        if (Token != null) {
            return true;
        }

        return StockToken();
    }

    private bool StockToken() {
        while (true) {
            sb.Clear();
            while (true) {
                if (cursor >= length) {
                    cursor = 0;
                    if ((length = Reader.Read(buffer, 0, buffer.Length)) <= 0) {
                        break;
                    }
                }
                var c = buffer[cursor++];
                if (33 <= c && c <= 126) {
                    sb.Append(c);
                } else {
                    if (sb.Length > 0) break;
                }
            }

            if (sb.Length > 0) {
                Token = sb.ToString();
                return true;
            }

            return false;
        }
    }
}


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

using E = System.Linq.Enumerable;
using System.Threading;
using System.Numerics;

internal partial class Solver {
    public void Run() {
        var m = nl();
        var x = nl();

        cout.WriteLine(Solve(m, x));
    }

    /*
    Sample 1
    0 -> 0
    1 -> 3 -> 1 -> 3
    2 -> 2 -> 2 -> 2 (2*3^x%4 --> 3^x%2 と等化)
    3 -> 1 -> 3 -> 1

    g = gcd(start, M) ごとに場合分けすればよい
    start' = start / g
    M' = M / g
    start, start * x, ... start * x^k % M ->
    (start/g), start, ... start * x^k % M')
    start', start' * x, ... start' * x^k % M'

     * */

    public List<long> Factorize(long x) {
        var res = new List<long>();
        for (long i = 2; i * i <= x; i++) {
            if (x % i == 0) {
                res.Add(i);
                while (x % i == 0) x /= i;
            }
        }
        if (x != 1) res.Add(x);
        return res;
    }

    /// <returns>
    /// return min d where a^d = 1 (mod m)
    /// </returns>
    private long MultiplicativeOrder(IEnumerable<long> primes, long a, long m) {
        var phi = Phi(primes, m);
        var res = phi;
        foreach (var p in primes) {
            if (p > phi) break;
            while (res % p == 0 && BigInteger.ModPow(a, res / p, m) == 1) {
                res /= p;
                phi /= p;
            }
            while (phi % p == 0) phi /= p;
        }
        if (phi > 1 && BigInteger.ModPow(a, res / phi, m) == 1) {
            res /= phi;
        }
        return res;
    }

    private long Solve(long m, long x) {
        // from i to (i*x)%m
        long ans = 0;
        // x^phi(m) = 1 (mod m)
        var primes = Factorize(m);
        var len = primes.Count;
        for (int i = 0; i < len; i++) {
            primes.AddRange(Factorize(primes[i] - 1));
        }
        primes.Sort();
        primes = primes.Distinct().ToList();

        foreach (var g in Divisors(m)) {
            var m2 = m / g;
            var phi = Phi(m2);
            ans += phi / MultiplicativeOrder(primes, x, m2);
        }
        return ans;
    }

    public static long ModPow(long x, long n, long mod) {
        long t = x, ret = 1;
        while (n > 0) {
            if ((n & 1) != 0) {
                ret = (long)(((decimal)t * ret) % mod);
            }
            t = (long)((decimal)t * t % mod);
            n >>= 1;
        }
        return ret;
    }

    public static long Phi(IEnumerable<long> primes, long n) {
        long phi = n;

        foreach (var p in primes) {
            if (p * p > n) break;
            if (n % p == 0) {
                while (n % p == 0) {
                    n /= p;
                }
                phi = phi / p * (p - 1);
            }
        }

        if (n > 1) {
            phi = phi / n * (n - 1);
        }

        return phi;
    }
    public static long Phi(long n) {
        long phi = n;

        for (long i = 2; i * i <= n && i < n; i++) {
            if (n % i == 0) {
                while (n % i == 0) {
                    n /= i;
                }

                phi = phi / i * (i - 1);
            }
        }
        if (n > 1) {
            phi = phi / n * (n - 1);
        }

        return phi;
    }

    Dictionary<long, List<long>> cache = new Dictionary<long, List<long>>();

    public List<long> Divisors(PrimeSet primes, long x) {
        //if (cache.TryGetValue(x, out var res)) return res;
        var ret = new List<long> { 1 };
        foreach (var p in primes) {
            if (p * p > x) break;
            int last = 0;
            while (x % p == 0) {
                int count = ret.Count;
                for (int i = last; i < count; i++) {
                    ret.Add(ret[i] * p);
                }
                last = count;
                x /= p;
            }
        }
        if (x != 1) {
            int count = ret.Count;
            for (int i = 0; i < count; i++) {
                ret.Add(ret[i] * x);
            }
        }
        cache[x] = ret;
        return ret;
    }

    public List<long> Divisors(long x) {
        if (cache.TryGetValue(x, out var res)) return res;
        var ret = new List<long>();
        for (long i = 1; i * i <= x; i++) {
            if (x % i == 0) {
                ret.Add(i);
                if (i != x / i) {
                    ret.Add(x / i);
                }
            }
        }
        ret.Sort();
        cache[x] = ret;
        return ret;
    }

}

public class PrimeSet : List<int> {
    private readonly bool[] isPrime;

    public PrimeSet(int size)
        : base() {
        isPrime = Enumerable.Repeat(true, size).ToArray();
        Add(2);
        for (int i = 3; i <= size; i += 2) {
            if (!isPrime[i >> 1]) {
                continue;
            }

            Add(i);
            for (long j = (long)i * i; j <= size; j += i + i) {
                isPrime[j >> 1] = false;
            }
        }
    }

    public bool IsPrime(long x) {
        if (x == 2) {
            return true;
        }

        if (x <= 1 || x % 2 == 0) {
            return false;
        }

        return isPrime[x >> 1];
    }
}

// PREWRITEN CODE BEGINS FROM HERE

static public class StringExtensions {
    static public string JoinToString<T>(this IEnumerable<T> source, string separator = " ") {
        return string.Join(separator, source);
    }
}

internal partial class Solver : Scanner {
    static readonly int? StackSizeInMebiByte = null; //50;
    public static void StartAndJoin(Action action, int maxStackSize) {
        var thread = new Thread(new ThreadStart(action), maxStackSize);
        thread.Start();
        thread.Join();
    }

    public static void Main() {
#if LOCAL
        byte[] inputBuffer = new byte[1000000];
        var inputStream = Console.OpenStandardInput(inputBuffer.Length);
        using (var reader = new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length)) {
            Console.SetIn(reader);
            new Solver(Console.In, Console.Out).Run();
        }
#else
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        if (StackSizeInMebiByte.HasValue) {
            StartAndJoin(() => new Solver(Console.In, Console.Out).Run(), StackSizeInMebiByte.Value * 1024 * 1024);
        } else {
            new Solver(Console.In, Console.Out).Run();
        }
        Console.Out.Flush();
#endif
    }

#pragma warning disable IDE0052
    private readonly TextReader cin;
    private readonly TextWriter cout;
    private readonly TextWriter cerr;
#pragma warning restore IDE0052

    public Solver(TextReader reader, TextWriter writer)
        : base(reader) {
        cin = reader;
        cout = writer;
        cerr = Console.Error;
    }

    public Solver(string input, TextWriter writer)
        : this(new StringReader(input), writer) {
    }

#pragma warning disable IDE1006
#pragma warning disable IDE0051
    private int ni() { return NextInt(); }
    private int[] ni(int n) { return NextIntArray(n); }
    private long nl() { return NextLong(); }
    private long[] nl(int n) { return NextLongArray(n); }
    private double nd() { return NextDouble(); }
    private double[] nd(int n) { return NextDoubleArray(n); }
    private string ns() { return Next(); }
    private string[] ns(int n) { return NextArray(n); }
#pragma warning restore IDE1006
#pragma warning restore IDE0051
}

#if DEBUG
internal static class LinqPadExtension {
    public static string TextDump<T>(this T obj) {
        if (obj is IEnumerable) return (obj as IEnumerable).Cast<object>().JoinToString().Dump();
        else return obj.ToString().Dump();
    }
    public static T Dump<T>(this T obj) {
        return LINQPad.Extensions.Dump(obj);
    }
}
#endif

public class Scanner {
    private readonly TextReader Reader;
    private readonly CultureInfo ci = CultureInfo.InvariantCulture;

    private readonly char[] buffer = new char[2 * 1024];
    private int cursor = 0, length = 0;
    private string Token;
    private readonly StringBuilder sb = new StringBuilder(1024);

    public Scanner()
        : this(Console.In) {
    }

    public Scanner(TextReader reader) {
        Reader = reader;
    }

    public int NextInt() { return checked((int)NextLong()); }
    public long NextLong() {
        var s = Next();
        long r = 0;
        int i = 0;
        bool negative = false;
        if (s[i] == '-') {
            negative = true;
            i++;
        }
        for (; i < s.Length; i++) {
            r = r * 10 + (s[i] - '0');
#if DEBUG
            if (!char.IsDigit(s[i])) throw new FormatException();
#endif
        }
        return negative ? -r : r;
    }
    public double NextDouble() { return double.Parse(Next(), ci); }
    public string[] NextArray(int size) {
        string[] array = new string[size];
        for (int i = 0; i < size; i++) {
            array[i] = Next();
        }

        return array;
    }
    public int[] NextIntArray(int size) {
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextInt();
        }

        return array;
    }

    public long[] NextLongArray(int size) {
        long[] array = new long[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextLong();
        }

        return array;
    }

    public double[] NextDoubleArray(int size) {
        double[] array = new double[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextDouble();
        }

        return array;
    }

    public string Next() {
        if (Token == null) {
            if (!StockToken()) {
                throw new Exception();
            }
        }
        var token = Token;
        Token = null;
        return token;
    }

    public bool HasNext() {
        if (Token != null) {
            return true;
        }

        return StockToken();
    }

    private bool StockToken() {
        while (true) {
            sb.Clear();
            while (true) {
                if (cursor >= length) {
                    cursor = 0;
                    if ((length = Reader.Read(buffer, 0, buffer.Length)) <= 0) {
                        break;
                    }
                }
                var c = buffer[cursor++];
                if (33 <= c && c <= 126) {
                    sb.Append(c);
                } else {
                    if (sb.Length > 0) break;
                }
            }

            if (sb.Length > 0) {
                Token = sb.ToString();
                return true;
            }

            return false;
        }
    }
}


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

using E = System.Linq.Enumerable;
using System.Threading;

internal partial class Solver {
    public void Run() {
        var m = nl();
        var x = nl();

        cout.WriteLine(Solve(m, x));
    }

    /*
    Sample 1
    0 -> 0
    1 -> 3 -> 1 -> 3
    2 -> 2 -> 2 -> 2 (2*3^x%4 --> 3^x%2 と等化)
    3 -> 1 -> 3 -> 1

    g = gcd(start, M) ごとに場合分けすればよい
    start' = start / g
    M' = M / g
    start, start * x, ... start * x^k % M ->
    (start/g), start, ... start * x^k % M')
    start', start' * x, ... start' * x^k % M'

     * */

    private long Solve(long m, long x) {
        // from i to (i*x)%m
        long ans = 1; // for 0-room

        // x^phi(m) = 1 (mod m)
        foreach (var g in Divisors(m)) {
            var m2 = m / g;
            long minPower = long.MaxValue;
            foreach (var p in Divisors(Phi(m2))) {
                if (ModPow(x, p, m2) == 1) {
                    minPower = p;
                    break;
                }
            }
            var startNum = (m - 1) / g;
            ans += startNum / minPower;
        }
        return ans;
    }

    public static long ModMultiple(long x, long n, long mod) {
        long t = x, ret = 0;
        while (n > 0) {
            if ((n & 1) != 0) {
                ret += t;
                if (ret >= mod) ret -= mod;
            }
            t <<= 1;
            if (t >= mod) t -= mod;
            n >>= 1;
        }
        return ret;
    }

    public static long ModPow(long x, long n, long mod) {
        long t = x, ret = 1;
        t %= mod;
        while (n > 0) {
            if ((n & 1) != 0) {
                //ret = (t * ret) % mod;
                ret = ModMultiple(t, ret, mod);
            }
            //t = t * t % mod;
            t = ModMultiple(t, t, mod);
            n >>= 1;
        }
        return ret;
    }

    public static long Phi(long n) {
        long phi = n;

        for (long i = 2; i * i <= n && i < n; i++) {
            if (n % i == 0) {
                while (n % i == 0) {
                    n /= i;
                }

                phi = phi / i * (i - 1);
            }
        }
        if (n > 1) {
            phi = phi / n * (n - 1);
        }

        return phi;
    }

    public static List<long> Divisors(long x) {
        var ret = new List<long>();
        for (long i = 1; i * i <= x; i++) {
            if (x % i == 0) {
                ret.Add(i);
                if (i != x / i) {
                    ret.Add(x / i);
                }
            }
        }
        ret.Sort();
        return ret;
    }

}

// PREWRITEN CODE BEGINS FROM HERE

static public class StringExtensions {
    static public string JoinToString<T>(this IEnumerable<T> source, string separator = " ") {
        return string.Join(separator, source);
    }
}

internal partial class Solver : Scanner {
    static readonly int? StackSizeInMebiByte = null; //50;
    public static void StartAndJoin(Action action, int maxStackSize) {
        var thread = new Thread(new ThreadStart(action), maxStackSize);
        thread.Start();
        thread.Join();
    }

    public static void Main() {
#if LOCAL
        byte[] inputBuffer = new byte[1000000];
        var inputStream = Console.OpenStandardInput(inputBuffer.Length);
        using (var reader = new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length)) {
            Console.SetIn(reader);
            new Solver(Console.In, Console.Out).Run();
        }
#else
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        if (StackSizeInMebiByte.HasValue) {
            StartAndJoin(() => new Solver(Console.In, Console.Out).Run(), StackSizeInMebiByte.Value * 1024 * 1024);
        } else {
            new Solver(Console.In, Console.Out).Run();
        }
        Console.Out.Flush();
#endif
    }

#pragma warning disable IDE0052
    private readonly TextReader cin;
    private readonly TextWriter cout;
    private readonly TextWriter cerr;
#pragma warning restore IDE0052

    public Solver(TextReader reader, TextWriter writer)
        : base(reader) {
        cin = reader;
        cout = writer;
        cerr = Console.Error;
    }

    public Solver(string input, TextWriter writer)
        : this(new StringReader(input), writer) {
    }

#pragma warning disable IDE1006
#pragma warning disable IDE0051
    private int ni() { return NextInt(); }
    private int[] ni(int n) { return NextIntArray(n); }
    private long nl() { return NextLong(); }
    private long[] nl(int n) { return NextLongArray(n); }
    private double nd() { return NextDouble(); }
    private double[] nd(int n) { return NextDoubleArray(n); }
    private string ns() { return Next(); }
    private string[] ns(int n) { return NextArray(n); }
#pragma warning restore IDE1006
#pragma warning restore IDE0051
}

#if DEBUG
internal static class LinqPadExtension {
    public static string TextDump<T>(this T obj) {
        if (obj is IEnumerable) return (obj as IEnumerable).Cast<object>().JoinToString().Dump();
        else return obj.ToString().Dump();
    }
    public static T Dump<T>(this T obj) {
        return LINQPad.Extensions.Dump(obj);
    }
}
#endif

public class Scanner {
    private readonly TextReader Reader;
    private readonly CultureInfo ci = CultureInfo.InvariantCulture;

    private readonly char[] buffer = new char[2 * 1024];
    private int cursor = 0, length = 0;
    private string Token;
    private readonly StringBuilder sb = new StringBuilder(1024);

    public Scanner()
        : this(Console.In) {
    }

    public Scanner(TextReader reader) {
        Reader = reader;
    }

    public int NextInt() { return checked((int)NextLong()); }
    public long NextLong() {
        var s = Next();
        long r = 0;
        int i = 0;
        bool negative = false;
        if (s[i] == '-') {
            negative = true;
            i++;
        }
        for (; i < s.Length; i++) {
            r = r * 10 + (s[i] - '0');
#if DEBUG
            if (!char.IsDigit(s[i])) throw new FormatException();
#endif
        }
        return negative ? -r : r;
    }
    public double NextDouble() { return double.Parse(Next(), ci); }
    public string[] NextArray(int size) {
        string[] array = new string[size];
        for (int i = 0; i < size; i++) {
            array[i] = Next();
        }

        return array;
    }
    public int[] NextIntArray(int size) {
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextInt();
        }

        return array;
    }

    public long[] NextLongArray(int size) {
        long[] array = new long[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextLong();
        }

        return array;
    }

    public double[] NextDoubleArray(int size) {
        double[] array = new double[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextDouble();
        }

        return array;
    }

    public string Next() {
        if (Token == null) {
            if (!StockToken()) {
                throw new Exception();
            }
        }
        var token = Token;
        Token = null;
        return token;
    }

    public bool HasNext() {
        if (Token != null) {
            return true;
        }

        return StockToken();
    }

    private bool StockToken() {
        while (true) {
            sb.Clear();
            while (true) {
                if (cursor >= length) {
                    cursor = 0;
                    if ((length = Reader.Read(buffer, 0, buffer.Length)) <= 0) {
                        break;
                    }
                }
                var c = buffer[cursor++];
                if (33 <= c && c <= 126) {
                    sb.Append(c);
                } else {
                    if (sb.Length > 0) break;
                }
            }

            if (sb.Length > 0) {
                Token = sb.ToString();
                return true;
            }

            return false;
        }
    }
}


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
{
    public void Solve()
    {
        int x = ReadInt();
        var a = Convert.ToString(x, 2).ToList();
        while (a.Count < 6)
            a.Insert(0, '0');

        char t = a[1];
        a[1] = a[5];
        a[5] = t;
        t = a[2];
        a[2] = a[3];
        a[3] = t;
        Write(Convert.ToInt32(new string(a.ToArray()), 2));
    }

    #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("input.txt");
        //writer = new StreamWriter("output.txt");
#endif
        try
        {
            new Solver().Solve();
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine(ex);
#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;

namespace prC {
    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[] map = {0, 5, 3, 2, 4, 1};
            int n = NextInt();
            int i = 5;
            int[] nn = new int[6];
            while (n > 0) {
                nn[i] = n & 1;
                i--;
                n >>= 1;
            }
            int r = 0;
            for (int j = 0; j < 6; j++) {
                r <<= 1;
                r += nn[map[j]];
            }
            writer.Write(r);

            writer.Flush();
#if !ONLINE_JUDGE
            writer.Close();
#endif
        }
        private static int NextInt() {
            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';
            }
        }
        private static long NextLong() {
            int c;
            long 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.Linq;

namespace a
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = int.Parse(Console.ReadLine());

            var a = Convert.ToString(x, 2).PadLeft(6, '0').ToArray();

            var temp = a[1];
            a[1] = a[5];
            a[5] = temp;
            temp = a[2];
            a[2] = a[3];
            a[3] = temp;

            Console.WriteLine(Convert.ToInt32(new String(a), 2));
        }
    }
}


using System;

public class Test
{
	public static void Main()
	{
		var x = int.Parse(Console.ReadLine());

		var a = Convert.ToString(x, 2).PadLeft(6, '0').ToArray();

		var temp = a[0];
		a[0] = a[4];
		a[4] = temp;
		temp = a[1];
		a[1] = a[2];
		a[2] = temp;

		Console.WriteLine(Convert.ToInt32(new String(a), 2));

	}
}


using System;

public class Test
{
	public static void Main()
	{
		var x = int.Parse(Console.ReadLine());

		var a = Convert.ToString(x, 2).PadLeft(6, '0');

		var temp = a[0];
		a[0] = a[4];
		a[4] = temp;
		temp = a[1];
		a[1] = a[2];
		a[2] = temp;

		Console.WriteLine(Convert.ToInt32(a, 2));

	}
}


using System;
using System.Linq;

public class Test
{
	public static void Main()
	{
		var x = int.Parse(Console.ReadLine());

		var a = Convert.ToString(x, 2).PadLeft(6, '0').ToArray();

		var temp = a[0];
		a[0] = a[4];
		a[4] = temp;
		temp = a[1];
		a[1] = a[2];
		a[2] = temp;

		Console.WriteLine(Convert.ToInt32(new String(a), 2));

	}
}


using System;
using System.Collections.Generic;
using static System.Console;
using System.Linq;

class edf116
{
    static int NN => int.Parse(ReadLine());
    static int[] NList => ReadLine().Split().Select(int.Parse).ToArray();
    static int[][] NArr(int n) => Enumerable.Repeat(0, n).Select(_ => NList).ToArray();
    static void Main()
    {
        var c = NList;
        var (n, x) = (c[0], c[1]);
        WriteLine(Arena(n, x));
    }
    static long Arena(int n, int x)
    {
        var key = 998244353;
        var ncr = new NCR(Math.Max(n, x), key);
        var exp = new long[n + 1][];
        for (var i = 0; i < exp.Length; ++i)
        {
            exp[i] = new long[n + 1];
            for (var j = 0; j < exp.Length; ++j) exp[i][j] = ncr.Exp(i, j);
        }
        var dp = new long[x][];
        for (var i = 0; i < dp.Length; ++i)
        {
            dp[i] = new long[n];
            dp[i][0] = n;
        }
        for (var i = 0; i < x; ++i) for (var j = 0; j < n; ++j)
        {
            for (var k = j; k < n; ++k)
            {
                if (i + k >= x) break;
                var prev = dp[i + k][k];
                if (j == 0 && k == 0) continue;
                else if (j == k)
                {
                    dp[i + k][k] = (dp[i + k][k] + dp[i][j]) % key;
                }
                else
                {
                    dp[i + k][k] = (dp[i + k][k]
                        + dp[i][j] * ncr.Calc(n - j - 1, k - j) % key * exp[k][k - j] % key) % key;
                }
            }
        }
        var res = 0L;
        for (var i = 0; i < x; ++i) res = (res + dp[i][n - 1]) % key;
        return (ncr.Exp(x, n) + key - res) % key;
    }
    class NCR
    {
        int[] facts;
        int[] revFacts;
        int key;
        public NCR(int n, int key)
        {
            facts = new int[n + 1];
            revFacts = new int[n + 1];
            this.key = key;
            facts[0] = 1;
            var tmp = 1L;
            for (var i = 1; i <= n; ++i)
            {
                tmp = (tmp * i) % key;
                facts[i] = (int)tmp;
            }
            tmp = Exp(facts[n], key - 2);
            revFacts[n] = (int)tmp;
            for (var i = n; i > 1; --i)
            {
                tmp = (tmp * i) % key;
                revFacts[i - 1] = (int)tmp;
            }
        }
        public long Exp(int n, int k)
        {
            if (k == 0) return 1;
            if (k == 1) return n % key;
            var half = Exp(n, k / 2);
            var result = (half * half) % key;
            return ((k % 2) == 0) ? result : ((result * n) % key);
        }
        public int Calc(int n, int r)
        {
            if (r == 0 || r == n) return 1;
            if (r == 1) return n;
            return (int)(((long)facts[n] * revFacts[r] % key) * revFacts[n - r] % key);
        }
        public int Fact(int n)
        {
            return facts[n];
        }
    }
}


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

public class Program
{
    int N, X;
    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        X = sc.NextInt();

        //int ans = 0;
        //for (int i = 1; i <= 3; i++)
        //{
        //    for (int j = 1; j <= 3; j++)
        //    {
        //        for (int k = 1; k <= 3; k++)
        //        {
        //            int[] h = new int[3] { i, j, k };

        //            if (F(h))
        //            {
        //                ans++;
        //                Console.WriteLine(string.Join(" ", h));
        //            }
        //        }
        //    }
        //}

        //Console.WriteLine(ans);

        var c = new BinomialCoefficient(5000);
        // 残りi人　最大体力j
        var dp = new ModInt[N + 1, X + 1];
        for (int i = 2; i <= N; i++)
        {
            for (int j = 1; j < i && j <= X; j++)
            {
                ModInt tmp = ModInt.Pow(j, i) - ModInt.Pow(j - 1, i);
                dp[i, j] += tmp;
            }
        }

        for (int i = 2; i <= N; i++)
        {
            for (int j = 1; j <= X; j++)
            {
                for (int k = i; k <= N; k++)
                {
                    // k人の状態から (i,j)になった

                    // i人の体力 k-1減る
                    if (j + (k - 1) > X) continue;

                    // k-i人 (k-1)減る
                    dp[k, j + (k - 1)] += dp[i, j] * ModInt.Pow(k - 1, k - i) * c[k, i];
                }
            }
        }

        ModInt ans = 0;
        for (int i = 1; i <= X; i++)
        {
            ans += dp[N, i];
        }
        Console.WriteLine(ans);

        //for (int i = 0; i <= N; i++)
        //{
        //    for (int j = 0; j <= X; j++)
        //    {
        //        Console.Write($"{dp[i, j]} ");
        //    }
        //    Console.WriteLine();
        //}
    }

    bool F(int[] ar)
    {
        if (ar.Length == 0) return true;
        if (ar.Length == 1) return false;
        List<int> ls = new List<int>();
        foreach (int i in ar)
        {
            if (i - ar.Length + 1 > 0)
            {
                ls.Add(i - ar.Length + 1);
            }
        }

        return F(ls.ToArray());
    }

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

// https://bitbucket.org/camypaper/complib
namespace CompLib.Mathematics
{
    #region ModInt
    /// <summary>
    /// [0,<see cref="Mod"/>) までの値を取るような数
    /// </summary>
    public struct ModInt
    {
        /// <summary>
        /// 剰余を取る値．
        /// </summary>
        // public const long Mod = (int)1e9 + 7;
        public const long Mod = 998244353;

        /// <summary>
        /// 実際の数値．
        /// </summary>
        public long num;
        /// <summary>
        /// 値が <paramref name="n"/> であるようなインスタンスを構築します．
        /// </summary>
        /// <param name="n">インスタンスが持つ値</param>
        /// <remarks>パフォーマンスの問題上，コンストラクタ内では剰余を取りません．そのため，<paramref name="n"/> ∈ [0,<see cref="Mod"/>) を満たすような <paramref name="n"/> を渡してください．このコンストラクタは O(1) で実行されます．</remarks>
        public ModInt(long n) { num = n; }
        /// <summary>
        /// このインスタンスの数値を文字列に変換します．
        /// </summary>
        /// <returns>[0,<see cref="Mod"/>) の範囲内の整数を 10 進表記したもの．</returns>
        public override string ToString() { return num.ToString(); }
        public static ModInt operator +(ModInt l, ModInt r) { l.num += r.num; if (l.num >= Mod) l.num -= Mod; return l; }
        public static ModInt operator -(ModInt l, ModInt r) { l.num -= r.num; if (l.num < 0) l.num += Mod; return l; }
        public static ModInt operator *(ModInt l, ModInt r) { return new ModInt(l.num * r.num % Mod); }
        public static implicit operator ModInt(long n) { n %= Mod; if (n < 0) n += Mod; return new ModInt(n); }

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

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(long v, long k)
        {
            long ret = 1;
            for (k %= Mod - 1; k > 0; k >>= 1, v = v * v % Mod)
                if ((k & 1) == 1) ret = ret * v % Mod;
            return new ModInt(ret);
        }
        /// <summary>
        /// 与えられた数の逆元を計算します．
        /// </summary>
        /// <param name="v">逆元を取る対象となる数</param>
        /// <returns>逆元となるような値</returns>
        /// <remarks>法が素数であることを仮定して，フェルマーの小定理に従って逆元を O(log N) で計算します．</remarks>
        public static ModInt Inverse(ModInt v) { return Pow(v, Mod - 2); }
    }
    #endregion
    #region Binomial Coefficient
    public class BinomialCoefficient
    {
        public ModInt[] fact, ifact;
        public BinomialCoefficient(int n)
        {
            fact = new ModInt[n + 1];
            ifact = new ModInt[n + 1];
            fact[0] = 1;
            for (int i = 1; i <= n; i++)
                fact[i] = fact[i - 1] * i;
            ifact[n] = ModInt.Inverse(fact[n]);
            for (int i = n - 1; i >= 0; i--)
                ifact[i] = ifact[i + 1] * (i + 1);
            ifact[0] = ifact[1];
        }
        public ModInt this[int n, int r]
        {
            get
            {
                if (n < 0 || n >= fact.Length || r < 0 || r > n) return 0;
                return fact[n] * ifact[n - r] * ifact[r];
            }
        }
        public ModInt RepeatedCombination(int n, int k)
        {
            if (k == 0) return 1;
            return this[n + k - 1, k];
        }
    }
    #endregion
}

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

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

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

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

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

            return _line[_index++];
        }

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

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

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

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


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

namespace ConsoleApp9
{
    class Program
    {

        static long mod = 998244353L;
        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
            int n = input[0], x = input[1];
            var xar = new long[n + 1, n + 1];
            for (int i = 1; i <= n; i++)
            {
                xar[i, 0] = 1;
                for (int j = 1; j <= n; j++)
                    xar[i, j] = (xar[i, j - 1] * i)% mod;
            }
            var c = new long[n + 1, n + 1];
            c[0, 0] = 1;
            for(int i=1; i <= n; i++)
            {
                c[i, 0] = 1;
                for (int k = 1; k <= i; k++)
                    c[i, k] = (c[i - 1, k - 1] + c[i - 1, k]) % mod;
            }
            var mas = new long[n + 1, x + 1];
            for(int i=1; i <= n; i++)
            {
                for(int j = i; j <= x; j++)
                {
                    if( i == 1)
                    {
                        mas[i, j] = j;
                        continue;
                    }
                    for(int k =0; k < i; k++)
                        mas[i, j] = (mas[i, j] + (((xar[i - 1, k] * c[i, k])%mod) * mas[i - k, j - i + 1])%mod)%mod;
                }
            }
            long xn = 1;
            for (int i = 1; i <= n; i++)
                xn = (xn * x) % mod;
            var res = (xn - mas[n, x] + mod) % mod;
            Console.Write(res);
        }
    }
}


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

public class Matrix {
    public int Row, Col;
    private int[] Data;
    public Matrix(int row, int col) {
        this.Row = row;
        this.Col = col;
        this.Data = new int[Row * Col];
    }

    public int this[int row, int col] {
        set {
            Data[row * Col + col] = value;
        }
        get {
            return Data[row * Col + col];
        }
    }

    static public Matrix UnitMatrix(int n) {
        Matrix matrix = new Matrix(n, n);
        for (int i = 0; i < n; i++) {
            matrix[i, i] = 1;
        }
        return matrix;
    }

    static public Matrix operator +(Matrix A, Matrix B) {
        Matrix C = new Matrix(A.Row, A.Col);
        for (int i = 0; i < C.Data.Length; i++) {
            if (A.Data[i] == int.MaxValue || B.Data[i] == int.MaxValue)
                C.Data[i] = int.MaxValue;
            else
                C.Data[i] = A.Data[i] + B.Data[i];
        }
        return C;
    }

    static public Matrix operator -(Matrix A, Matrix B) {
        Matrix C = new Matrix(A.Row, A.Col);
        for (int i = 0; i < C.Data.Length; i++) {
            C.Data[i] = A.Data[i] - B.Data[i];
        }
        return C;
    }

    static public Matrix operator *(Matrix A, Matrix B) {
        Matrix C = new Matrix(A.Row, B.Col);
        for (int i = 0; i < A.Row; i++) {
            for (int j = 0; j < B.Col; j++) {
                C[i, j] = int.MaxValue;
                for (int k = 0; k < A.Col; k++) {
                    //C[i, j] += A[i, k] * B[k, j];
                    if (A[i, k] == int.MaxValue || B[k, j] == int.MaxValue) continue;
                    C[i, j] = Math.Min(C[i, j], A[i, k] + B[k, j]);
                }
            }
        }
        return C;
    }

    static public Matrix Pow(Matrix A, long n) {
        if (n == 0) return UnitMatrix(A.Row);
        Matrix result = A.Clone(), t = A.Clone(); n--;
        while (n > 0) {
            if ((n & 1) != 0) {
                result = result * t;
            }

            t = t * t;
            n >>= 1;
        }

        return result;
    }

    public Matrix Clone() {
        Matrix clone = new Matrix(Row, Col);
        clone.Data = Data.Clone() as int[];
        return clone;
    }
}

public partial class CodeForces {

    static void UpdateMin<T>(ref T x, T newValue) where T : IComparable<T> {
        if (x.CompareTo(newValue) > 0) x = newValue;
    }

    static public void Solve(TextReader cin, TextWriter cout) {
        var scanner = new Scanner(cin);
        int n = scanner.NextInt32();
        int m = scanner.NextInt32();
        var a = scanner.NextIntArray(n);
        var b = scanner.NextIntArray(n);
        int maxDepth = 2 * n + 1;
        var dp = new int[maxDepth, maxDepth];
        for (int i = 0; i < maxDepth; i++) {
            for (int j = 0; j < maxDepth; j++) {
                dp[i, j] = int.MaxValue;
            }
            dp[i, i] = 0;
        }
        for (int i = 0; i < n; i++) {
            var next = new int[maxDepth, maxDepth];
            for (int j = 0; j < maxDepth; j++) {
                for (int k = 0; k < maxDepth; k++) {
                    next[j, k] = int.MaxValue;
                }
            }
            for (int j = 0; j < maxDepth; j++) {
                for (int k = 0; k < maxDepth; k++) {
                    if (dp[j, k] == int.MaxValue) continue;
                    if (k + 1 < maxDepth)
                        UpdateMin(ref next[j, k + 1], dp[j, k] + a[i]);
                    if (k - 1 >= 0)
                        UpdateMin(ref next[j, k - 1], dp[j, k] + b[i]);
                }
            }

            dp = next;
        }

        /*for (int i = 0; i < maxDepth; i++) {
            for (int j = 0; j < maxDepth; j++) {
                Console.Error.Write(" " + dp[i, j]);
            }
            Console.Error.WriteLine();
        }*/

        Matrix M = new Matrix(maxDepth, maxDepth);

        for (int i = 0; i < maxDepth; i++) {
            for (int j = 0; j < maxDepth; j++) {
                M[i, j] = dp[i, j];
            }
        }

        Matrix A = M.Clone();

        A = Matrix.Pow(A, m);

        cout.WriteLine(A[0, 0]);
    }

    // PREWRITEN CODE BEGINS FROM HERE

    public static void Main(string[] args) {
#if ONLINE_JUDGE
        Solve(Console.In, Console.Out);
#else
        SampleTest();
#endif

    }

    static void SampleTest() {

        var Inputs = @"
2 6
1 2
2 1
------------
1 10000000
2
3
".Split(new[] { "------------" }, StringSplitOptions.None).Select(s => s.Trim()).ToArray();

        var Outputs = @"
12
------------
25000000
".Split(new[] { "------------" }, StringSplitOptions.None).Select(s => s.Trim()).ToArray();

        int caseNo = 1;
        int all = 0, passed = 0;
        foreach (var sample in Inputs.Zip(Outputs, (Input, Output) => new { Input, Output })) {
            var stopWatch = new System.Diagnostics.Stopwatch();
            var writer = new StringWriter();
            stopWatch.Start();
            Solve(new StringReader(sample.Input), writer);
            stopWatch.Stop();
            string time = "";
            if (stopWatch.ElapsedMilliseconds >= 10) {
                time = String.Format("({0} ms)", stopWatch.ElapsedMilliseconds);
            }
            var result = writer.ToString().Trim();
            all++;
            if (result == sample.Output) {
                Console.WriteLine("Sample {0} .... Passed {1}", caseNo++, time);
                passed++;
            } else {
                Console.WriteLine("Sample {0} .... Failed", caseNo++, time);
                Console.WriteLine("Input : ");
                Console.WriteLine("{0}", sample.Input);
                Console.WriteLine("Expected : ");
                Console.WriteLine("{0}", sample.Output);
                Console.WriteLine("Received : ");
                Console.WriteLine("{0}", result);
            }
        }

        Console.WriteLine(" {0} / {1} Passed !!", passed, all);

        Solve(Console.In, Console.Out);
    }

}

public class Scanner {
    private TextReader Reader;
    private Queue<String> TokenQueue = new Queue<string>();
    private CultureInfo ci = new CultureInfo("en-US");

    public Scanner()
        : this(Console.In) {
    }

    public Scanner(TextReader reader) {
        this.Reader = reader;
    }

    public char NextChar() { return Next().Single(); }
    public int NextInt32() { return Int32.Parse(Next(), ci); }
    public long NextInt64() { return Int64.Parse(Next(), ci); }
    public double NextDouble() { return double.Parse(Next(), ci); }
    public string[] NextArray(int size) {
        var array = new string[size];
        for (int i = 0; i < size; i++) array[i] = Next();
        return array;
    }
    public int[] NextIntArray(int size) {
        var array = new int[size];
        for (int i = 0; i < size; i++) array[i] = NextInt32();
        return array;
    }

    public long[] NextInt64Array(int size) {
        var array = new long[size];
        for (int i = 0; i < size; i++) array[i] = NextInt64();
        return array;
    }

    public String Next() {
        if (!TokenQueue.Any()) {
            if (!StockTokens()) throw new InvalidOperationException();
        }
        return TokenQueue.Dequeue();
    }

    public bool HasNext() {
        if (TokenQueue.Count > 0)
            return true;
        return StockTokens();
    }

    private bool StockTokens() {
        while (true) {
            var line = Reader.ReadLine();
            if (line == null) return false;
            var tokens = line.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToArray();
            if (tokens.Length == 0) continue;
            foreach (var token in tokens)
                TokenQueue.Enqueue(token);
            return true;
        }
    }
}


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

public class Matrix {
    public int Row, Col;
    private int[] Data;
    public Matrix(int row, int col) {
        this.Row = row;
        this.Col = col;
        this.Data = new int[Row * Col];
    }

    public int this[int row, int col] {
        set {
            Data[row * Col + col] = value;
        }
        get {
            return Data[row * Col + col];
        }
    }

    static public Matrix operator +(Matrix A, Matrix B) {
        Matrix C = new Matrix(A.Row, A.Col);
        for (int i = 0; i < C.Data.Length; i++) {
            if (A.Data[i] == int.MaxValue || B.Data[i] == int.MaxValue)
                C.Data[i] = int.MaxValue;
            else
                C.Data[i] = A.Data[i] + B.Data[i];
        }
        return C;
    }

    static public Matrix operator -(Matrix A, Matrix B) {
        Matrix C = new Matrix(A.Row, A.Col);
        for (int i = 0; i < C.Data.Length; i++) {
            C.Data[i] = A.Data[i] - B.Data[i];
        }
        return C;
    }

    static public Matrix operator *(Matrix A, Matrix B) {
        Matrix C = new Matrix(A.Row, B.Col);
        for (int i = 0; i < A.Row; i++)
            for (int j = 0; j < B.Col; j++)
                C[i, j] = int.MaxValue;
        for (int i = 0; i < A.Row; i++) {
            for (int k = 0; k < A.Col; k++) {
                if (A[i, k] == int.MaxValue) continue;
                for (int j = 0; j < B.Col; j++) {
                    if (B[k, j] == int.MaxValue) continue;
                    C[i, j] = Math.Min(C[i, j], A[i, k] + B[k, j]);
                }
            }
        }
        return C;
    }

    static public Matrix Pow(Matrix A, long n) {
        Matrix result = A.Clone(), t = A.Clone(); n--;
        while (n > 0) {
            if ((n & 1) != 0) {
                result = result * t;
            }
            t = t * t;
            n >>= 1;
        }

        return result;
    }

    public Matrix Clone() {
        Matrix clone = new Matrix(Row, Col);
        clone.Data = Data.Clone() as int[];
        return clone;
    }
}

public partial class CodeForces {

    static void UpdateMin<T>(ref T x, T newValue) where T : IComparable<T> {
        if (x.CompareTo(newValue) > 0) x = newValue;
    }

    static public void Solve(TextReader cin, TextWriter cout) {
        var scanner = new Scanner(cin);
        int n = scanner.NextInt32();
        int m = scanner.NextInt32();
        var a = scanner.NextIntArray(n);
        var b = scanner.NextIntArray(n);
        int maxDepth = 2 * n + 1;
        var dp = new int[maxDepth, maxDepth];
        for (int i = 0; i < maxDepth; i++) {
            for (int j = 0; j < maxDepth; j++) {
                dp[i, j] = int.MaxValue;
            }
            dp[i, i] = 0;
        }
        for (int i = 0; i < n; i++) {
            var next = new int[maxDepth, maxDepth];
            for (int j = 0; j < maxDepth; j++) {
                for (int k = 0; k < maxDepth; k++) {
                    next[j, k] = int.MaxValue;
                }
            }
            for (int j = 0; j < maxDepth; j++) {
                for (int k = 0; k < maxDepth; k++) {
                    if (dp[j, k] == int.MaxValue) continue;
                    if (k + 1 < maxDepth)
                        UpdateMin(ref next[j, k + 1], dp[j, k] + a[i]);
                    if (k - 1 >= 0)
                        UpdateMin(ref next[j, k - 1], dp[j, k] + b[i]);
                }
            }

            dp = next;
        }

        /*for (int i = 0; i < maxDepth; i++) {
            for (int j = 0; j < maxDepth; j++) {
                Console.Error.Write(" " + dp[i, j]);
            }
            Console.Error.WriteLine();
        }*/

        Matrix M = new Matrix(maxDepth, maxDepth);

        for (int i = 0; i < maxDepth; i++) {
            for (int j = 0; j < maxDepth; j++) {
                M[i, j] = dp[i, j];
            }
        }

        Matrix A = M.Clone();

        A = Matrix.Pow(A, m);

        cout.WriteLine(A[0, 0]);
    }

    // PREWRITEN CODE BEGINS FROM HERE

    public static void Main(string[] args) {
#if ONLINE_JUDGE
        Solve(Console.In, Console.Out);
#else
        SampleTest();
#endif

    }

    static void SampleTest() {

        var Inputs = @"
2 6
1 2
2 1
------------
1 10000000
2
3
".Split(new[] { "------------" }, StringSplitOptions.None).Select(s => s.Trim()).ToArray();

        var Outputs = @"
12
------------
25000000
".Split(new[] { "------------" }, StringSplitOptions.None).Select(s => s.Trim()).ToArray();

        int caseNo = 1;
        int all = 0, passed = 0;
        foreach (var sample in Inputs.Zip(Outputs, (Input, Output) => new { Input, Output })) {
            var stopWatch = new System.Diagnostics.Stopwatch();
            var writer = new StringWriter();
            stopWatch.Start();
            Solve(new StringReader(sample.Input), writer);
            stopWatch.Stop();
            string time = "";
            if (stopWatch.ElapsedMilliseconds >= 10) {
                time = String.Format("({0} ms)", stopWatch.ElapsedMilliseconds);
            }
            var result = writer.ToString().Trim();
            all++;
            if (result == sample.Output) {
                Console.WriteLine("Sample {0} .... Passed {1}", caseNo++, time);
                passed++;
            } else {
                Console.WriteLine("Sample {0} .... Failed", caseNo++, time);
                Console.WriteLine("Input : ");
                Console.WriteLine("{0}", sample.Input);
                Console.WriteLine("Expected : ");
                Console.WriteLine("{0}", sample.Output);
                Console.WriteLine("Received : ");
                Console.WriteLine("{0}", result);
            }
        }

        Console.WriteLine(" {0} / {1} Passed !!", passed, all);

        Solve(Console.In, Console.Out);
    }

}

public class Scanner {
    private TextReader Reader;
    private Queue<String> TokenQueue = new Queue<string>();
    private CultureInfo ci = new CultureInfo("en-US");

    public Scanner()
        : this(Console.In) {
    }

    public Scanner(TextReader reader) {
        this.Reader = reader;
    }

    public char NextChar() { return Next().Single(); }
    public int NextInt32() { return Int32.Parse(Next(), ci); }
    public long NextInt64() { return Int64.Parse(Next(), ci); }
    public double NextDouble() { return double.Parse(Next(), ci); }
    public string[] NextArray(int size) {
        var array = new string[size];
        for (int i = 0; i < size; i++) array[i] = Next();
        return array;
    }
    public int[] NextIntArray(int size) {
        var array = new int[size];
        for (int i = 0; i < size; i++) array[i] = NextInt32();
        return array;
    }

    public long[] NextInt64Array(int size) {
        var array = new long[size];
        for (int i = 0; i < size; i++) array[i] = NextInt64();
        return array;
    }

    public String Next() {
        if (!TokenQueue.Any()) {
            if (!StockTokens()) throw new InvalidOperationException();
        }
        return TokenQueue.Dequeue();
    }

    public bool HasNext() {
        if (TokenQueue.Count > 0)
            return true;
        return StockTokens();
    }

    private bool StockTokens() {
        while (true) {
            var line = Reader.ReadLine();
            if (line == null) return false;
            var tokens = line.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToArray();
            if (tokens.Length == 0) continue;
            foreach (var token in tokens)
                TokenQueue.Enqueue(token);
            return true;
        }
    }
}


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

namespace cf558
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));
            solve_cf558A();
        }

        public static void solve_cf558A()
        {
            string[] nm = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(nm[0]);
            int m = Convert.ToInt32(nm[1]);
            m = m <= 1 ? 1 : m;

            int res = m <= n / 2 ? m: n - m;

            Console.WriteLine(res);
        }
    }
}


using System;

namespace testrun
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] values = Console.ReadLine().Split(' ');
            int n = int.Parse(values[0]);
            int m = int.Parse(values[1]);

            if (n == m)
            {
                System.Console.WriteLine(0);
                return;
            }

            if (m == 0)
            {
                System.Console.WriteLine(1);
                return;
            }

            int maxGroups = n / 2;
            int maxGroupsGap = n % 2 != 0 ? 1 : 0;

            if (m < maxGroups)
            {
                System.Console.WriteLine(m);
                return;
            }

            if (m > maxGroups + maxGroupsGap)
            {
                System.Console.WriteLine(maxGroups - (m - maxGroups - maxGroupsGap));
                return;
            }

            System.Console.WriteLine(maxGroups);
        }
    }
}


using System;
using System.Collections.Generic;
class Program
{
	static void Main(string[] args)
	{
		string[]str = Console.ReadLine().Split();
		int N = int.Parse(str[0]);
		int M = int.Parse(str[1]);
		int ans = 0;
		if(N==M){
			ans = 0;
		} else if(M==0){
		    ans = 1;
		} else {
		    int A = N-M;
			ans = Math.Min(M,A);
		}
		Console.WriteLine(ans);
	}
}


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

namespace test1
{
    class Program
    {
        static void Main(string[] args)
        {
            var st = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(st[0]), m = Convert.ToInt32(st[1]);
            int x = 0;
            if (n % 2 == 0)
            {
                if (m >= n / 2)
                {
                    x = n - m;
                }
                else if (m != 0)
                {
                    x = m;
                }
                else
                {
                    x = 1;
                }
            }
            else
            {
                if (m>n/2)
                {
                    x = n - m;
                }
                else if (m == n / 2)
                {
                    x = n - m - 1;
                }
                else if (m!=0)
                {
                    x = m;
                }
                else
                {
                    x = 1;
                }
            }
            Console.WriteLine(x);
        }
    }
}


using System;
using System.Linq;
using CompLib.Util;

public class Program
{

    public void Solve()
    {
        var sc = new Scanner();
        int n = sc.NextInt();
        int m = sc.NextInt();
        if(m == 0)
        {
            Console.WriteLine(1);
            return;
        }
        int k = n - m;
        Console.WriteLine(Math.Min(k, m));
    }

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

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

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

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

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

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

            return _line[_index++];
        }

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

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

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

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


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

namespace Eating_Soup
{
    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)
        {
            writer.WriteLine(Solve(args));
            writer.Flush();
        }

        private static int Solve(string[] args)
        {
            int n = Next();
            int m = Next();

            if (m < 2)
                return 1;

            if (n >= m*2)
                return m;
            if (n%2 == 1 && n == m*2 - 1)
            {
                return m - 1;
            }
            return n - m;
        }

        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.Text;

public class ansa{
    public static void Main() {
        //int n = Convert.ToInt32(Console.ReadLine());
        var num = Array.ConvertAll(Console.ReadLine().Trim().Split(), int.Parse);
        int ans;
        if(num[1]==0 || num[1]==1) ans = 1;
        else if(num[1]*2>=num[0]) ans = num[0] - num[1];
        else ans = num[1];
        Console.WriteLine(ans);
    }
}


#define USE_FILES
//#define MANY_TESTS_IN_INPUT
//#define INCREASE_STACK

#if ONLINE_JUDGE // Defined by Codeforces judging system
#undef USE_FILES
#endif

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

namespace Acm
{
    /// <summary>
    /// For the simplicity of hacking / reading / exploring.
    /// Problem solution is in this class only!
    /// </summary>
    class ProblemSolution
    {
        public LineReader In { get; }

        public TextWriter Out { get; }

        public ProblemSolution(LineReader @in, TextWriter @out)
        {
            In = @in;
            Out = @out;
        }

        /// <summary>
        /// </summary>
        /// <param name="testId">
        /// For multi-test inputs: ID of test, from 1 to T
        /// For single-test inputs: -1
        /// </param>
        public void SolveTest(int testId)
        {
	        int[] input = In.Read();
	        int n = input[0], m = input[1];

	        if (m == 0)
	        {
		        Out.WriteLine(1);
		        return;
	        }

	        int result = Math.Min(n - m, m);
	        Out.WriteLine(result);
        }
    }

    // ---------------
    // There is nothing interesting below this line!
    // ---------------

    class Program
    {
        private static LineReader In { get; set; }

        private static TextWriter Out { get; set; }

        public static void Main(string[] args)
        {
#if USE_FILES
            In = new LineReader(File.OpenText("input.txt"));
            Out = new StreamWriter("../../output.txt", false);
#else
            In = new LineReader(Console.In);
            Out = Console.Out;
#endif

                        try
            {
#if INCREASE_STACK
				var thread = new Thread(Solve, 32 * 1024 * 1024);
				thread.Start();
				thread.Join();
#else
                Solve();
#endif
            }
            finally
            {
                Out.Dispose();
            }
        }

        public static void Solve()
        {
#if MANY_TESTS_IN_INPUT
            int t = In.Read();
            for (int i = 1; i <= t; i++)
            {
                new ProblemSolution(In, Out).SolveTest(i);
            }
#else
            new ProblemSolution(In, Out).SolveTest(-1);
#endif
        }
    }

    /// <summary>
    /// Input usability things
    /// </summary>
    class InputLine
    {
        private readonly string _line;

        public InputLine(string line)
        {
            _line = line;
        }

        public static implicit operator string(InputLine line)
        {
            return line._line;
        }

        public static implicit operator int(InputLine line)
        {
            return int.Parse(line._line);
        }

        public static implicit operator int[] (InputLine line)
        {
            return line._line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
        }

        public static implicit operator long[] (InputLine line)
        {
            return line._line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
        }
    }

    class LineReader
    {
        public TextReader Reader { get; }

        public LineReader(TextReader reader)
        {
            Reader = reader;
        }

        public InputLine Read()
        {
            string line = Reader.ReadLine();
            return line == null
                ? null
                : new InputLine(line.Trim());
        }
    }
}


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

namespace ree
{
    class Program
    {
        static void Main()
        {
            string[] input = Console.ReadLine().Split();
            int n = int.Parse(input[0]);
            int m = int.Parse(input[1]);
            if (m == 0)
            {
                Console.WriteLine(1);
            }
            else if (m <= n / 2)
            {
                Console.WriteLine(m);
            }
            else
            {
                Console.WriteLine(n - m);
            }
        }
    }
}


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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Solve();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }

        static void Solve()
        {

            var nm = Console.ReadLine().Split(' ').Select(int.Parse).ToList();

            var n = nm[0];
            var m = nm[1];
            int left;
            if (n == m)
                left = 0;
            else if (m == 0)
                left = 1;
            else
                left = Math.Min(m, n - m);
            Console.WriteLine(left);

        }

    }
}


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

namespace ConsoleApp30
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr = Array.ConvertAll(Console.ReadLine().Trim().Split(),int.Parse);
            int answer = 0;
            answer = (arr[0] - arr[1]);
            if (arr[0] == arr[1])
            {
                Console.WriteLine(0);

            }
            else if (arr[1] == 0)
            {
                Console.WriteLine(1);
            }
            else
            {
                answer = Math.Min(arr[1], answer);
                Console.WriteLine(answer);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using static System.Math;

namespace Olymp
{
  public class ProblemSolver
  {
    private Tokenizer input;

    public void Solve()
    {
      var n = input.ReadInt();
      var m = input.ReadInt();
      Console.Write(m == 0 ? 1 : Min(n - m, m));
    }

    public ProblemSolver(TextReader input)
    {
      this.input = new Tokenizer(input);
    }

    #region Service functions

    private static int IncCount<T>(Dictionary<T, int> counter, T item)
    {
      if (counter.TryGetValue(item, out var count))
        return (counter[item] = count + 1);
      counter.Add(item, 1);
      return 1;
    }

    private static void DecCount<T>(Dictionary<T, int> counter, T item)
    {
      if (counter.TryGetValue(item, out var count))
      {
        if (count == 1)
          counter.Remove(item);
        else
          counter[item] = count - 1;
      }
    }

    private static int GetCount<T>(Dictionary<T, int> counter, T item)
    {
      return counter.TryGetValue(item, out var count) ? count : 0;
    }

    private static int GCD(int a, int b)
    {
      while (b != 0)
      {
        a %= b;
        var t = b;
        b = a;
        a = t;
      }
      return a;
    }

    #endregion
  }

  #region Service classes

  public class Tokenizer
  {
    private TextReader reader;

    public string ReadToEnd()
    {
      return this.reader.ReadToEnd();
    }

    public int ReadInt()
    {
      var c = SkipWS();
      if (c == -1)
        throw new EndOfStreamException();
      var isNegative = false;
      if (c == '-' || c == '+')
      {
        isNegative = c == '-';
        c = this.reader.Read();
        if (c == -1)
          throw new InvalidOperationException();
      }
      if (!char.IsDigit((char)c))
        throw new InvalidOperationException();
      var result = (char)c - '0';
      c = this.reader.Read();
      while (c > 0 && !char.IsWhiteSpace((char)c))
      {
        if (!char.IsDigit((char)c))
          throw new InvalidOperationException();
        result = result * 10 + (char)c - '0';
        c = this.reader.Read();
      }
      if (isNegative)
        result = -result;
      return result;
    }

    public string ReadLine()
    {
      return reader.ReadLine();
    }

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

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

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

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

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

    public string ReadToken()
    {
      var c = SkipWS();
      if (c == -1)
        return null;
      var sb = new StringBuilder();
      while (c > 0 && !char.IsWhiteSpace((char)c))
      {
        sb.Append((char)c);
        c = this.reader.Read();
      }
      return sb.ToString();
    }

    private int SkipWS()
    {
      var c = this.reader.Read();
      if (c == -1)
        return c;
      while (c > 0 && char.IsWhiteSpace((char)c))
        c = this.reader.Read();
      return c;
    }

    public Tokenizer(TextReader reader)
    {
      this.reader = reader;
    }
  }

  internal class Program
  {
    public static void Main(string[] args)
    {
      var solver = new ProblemSolver(Console.In);
      solver.Solve();
    }
  }

  #endregion
}


using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Numerics;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using static System.Math;
using Debug = System.Diagnostics.Debug;
using System.Runtime.CompilerServices;
using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;
using MethodImplAttribute = System.Runtime.CompilerServices.MethodImplAttribute;

static class P
{
    static void Main()
    {
        var nm = Console.ReadLine().Split().Select(int.Parse).ToArray();
        var n = nm[0];
        var m = nm[1];
        Console.WriteLine(Min(Max(1, m), n - m));
    }
}


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

namespace CSharpConsoleProject2
{

    class Sudoku
    {
        static void Main(string[] args)
        {
            int n = 0, m = 0;
            string str = Console.ReadLine();

            n = Convert.ToInt32(str.Split(' ')[0]);
            m = Convert.ToInt32(str.Split(' ')[1]);

            int a = 0;

            if (m == 0)
            {
                a = 1;
            } else if (m == n)
            {
                a = 0;
            } else
            {
                a = m;
                if (a > (n - m))
                {
                    a = (n - m);
                }
            }

            Console.WriteLine(a);

        }
    }
}


using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string line = Console.ReadLine();
            int n = Convert.ToInt32(line.Split(' ')[0]);
            int m = Convert.ToInt32(line.Split(' ')[1]);
            int otvet;
            if(m == 0) {
                Console.WriteLine(1);
                return;
            }

            int x = n / 2;
            if (m <= x)
                otvet = m;
            else otvet = n - m;
            Console.WriteLine(otvet);
        }
    }
}


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

namespace ReadWriteTemplate
{
    public static class Solver
    {
        private static void SolveCase()
        {
            int n = ReadInt();
            int m = ReadInt();
            int ans = m == 0 ? 1 : Math.Min(m, n - m);
            Writer.WriteLine(ans);
        }

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

            SolveCase();

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

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

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

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

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

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

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

        public static T[] Shuffle<T>(this IEnumerable<T> source)
        {
            T[] result = source.ToArray();
            Shuffle(result);
            return result;
        }

        private static void Shuffle<T>(IList<T> array)
        {
            Random rnd = new Random();
            for (int i = array.Count - 1; i >= 1; i--)
            {
                int k = rnd.Next(i + 1);
                T tmp = array[k];
                array[k] = array[i];
                array[i] = tmp;
            }
        }

        #region Read/Write

        private static TextReader Reader;

        private static TextWriter Writer;

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

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

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

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

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

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

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

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

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

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

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

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

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

        #endregion
    }
}


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

namespace ACM
{
    class Program
    {
        static int Gcd(int a, int b)
        {
            return b != 0 ? Gcd(b, a % b) : a;
        }

        static int Solve(int n, int m)
        {
            if (m == 0)
            {
                return 1;
            }

            if (m == n)
            {
                return 0;
            }

            m--;
            int length = n - 1;
            int one = 0;
            while (m-- > 0)
            {
                if (length == 0)
                {
                    one--;
                }
                else if (length == 1)
                {
                    length--;
                }
                else if (length == 2)
                {
                    length--;
                }
                else
                {
                    length -= 2;
                    one++;
                }
            }

            if (length > 0)
            {
                one++;
            }

            return one;
        }

        static void Main(string[] args)
        {
            string[] token = Console.ReadLine().Split();
            int n = int.Parse(token[0]);
            int m = int.Parse(token[1]);
            Console.WriteLine(Solve(n, m));
        }
    }
}


using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
using System.Numerics;

class Solution
{

    static void Main(string[] args)
    {
        //var n = int.Parse(Console.ReadLine().Trim());
        var arr = Array.ConvertAll(Console.ReadLine().Trim().Split(), int.Parse);
        var n = arr[0];
        var m = arr[1];
        if (m == 0)
            Console.WriteLine(1);
        else if (m <= n / 2)
        {
            Console.WriteLine(m);
        }
        else
        {
            Console.WriteLine(n - m);
        }

    }

}


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

class Program
{
    static void Main()
    {
        var data = Console.ReadLine().Split();

        int a = int.Parse(data[0]);
        int b = int.Parse(data[1]);

        if (a >= 2 * b)
            if (b == 0)
            {
                Console.WriteLine(1);
            }
            else
            {
                Console.WriteLine(b);
            }
        else if (a > b)
            Console.WriteLine(a - b);
        else if (a <= b)
            Console.WriteLine(0);
        else
            Console.WriteLine(1);
    }
}


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

#if DEBUG
using System.Diagnostics;
#endif

namespace CompetitiveProgramming
{
    class Program
    {
        static bool s_IsMultipleTestCases = false;
        static void Main(string[] args)
        {
#if DEBUG
            s_IsMultipleTestCases = false;
            var streamReader = new StreamReader("../../input.txt", Encoding.ASCII, false, 32768);
            var streamWriter = new StreamWriter("../../output.txt", false, Encoding.ASCII, 32768);
            var timer = new Stopwatch();
#else
            var streamReader = new StreamReader(Console.OpenStandardInput(32768), Encoding.ASCII, false, 32768);
            var streamWriter = new StreamWriter(Console.OpenStandardOutput(32768), Encoding.ASCII, 32768);
#endif
            var reader = new InputReader(streamReader);

            var numberOfTest = 1;
            if (s_IsMultipleTestCases)
            {
                numberOfTest = reader.NextInt();
            }
            for (var testNumber = 1; testNumber <= numberOfTest; ++testNumber)
            {
#if DEBUG
                timer.Start();
#endif
                Task solver = new Task();
                solver.Solve(testNumber, reader, streamWriter);
#if DEBUG
                streamWriter.WriteLine("Eslapsed Time: " + timer.ElapsedMilliseconds + " ms\n");
                timer.Reset();
#endif
            }
            streamReader.Close();
            streamWriter.Close();
        }
    }

    class Task
    {
        public void Solve(int testNumber, InputReader reader, StreamWriter writer)
        {
            var n = reader.NextInt();
            var m = reader.NextInt();

            var res = 0;

            if(m == 0)
            {
                writer.WriteLine(1);
                return;
            }

            if(m <= n / 2)
            {
                res = m;
            }
            else if(n % 2  == 0)
            {
                res = n / 2 - (m - n / 2);
            }
            else
            {
                res = n / 2 - (m - 1 - n / 2);
            }

            writer.WriteLine(res);
        }

        #region Utilities
        private string ConvertArrayToString(int[] arrs)
        {
            var sb = new StringBuilder();
            foreach (var item in arrs)
            {
                sb.Append(item);
                sb.Append("\n");
            }
            return sb.ToString();
        }

        private string ConvertArrayToString(long[] arrs)
        {
            var sb = new StringBuilder();
            foreach (var item in arrs)
            {
                sb.Append(item);
                sb.Append("\n");
            }
            return sb.ToString();
        }

        private string ConvertDoubleToString(double x)
        {
            return x.ToString(CultureInfo.InvariantCulture);
        }

        private int Max(int a, int b)
        {
            return Math.Max(a, b);
        }

        private int Min(int a, int b)
        {
            return Math.Min(a, b);
        }

        private long Max(long a, long b)
        {
            return Math.Max(a, b);
        }

        private long Min(long a, long b)
        {
            return Math.Min(a, b);
        }

        private long GCD(long a, long b)
        {
            return a > 0 ? b : GCD(b, a % b);
        }

        private int GCD(int a, int b)
        {
            return a > 0 ? b : GCD(b, a % b);
        }

        #endregion
    }

    class InputReader
    {
        private char[] _inbuf;
        private int _lenbuf = 0, _ptrbuf = 0;
        private StreamReader _reader;

        public InputReader(StreamReader reader)
        {
            _reader = reader;
            _inbuf = new char[1024];
            _lenbuf = 0;
            _ptrbuf = 0;
        }

        private int ReadByte()
        {
            if (_lenbuf == -1)
                throw new Exception();
            if (_ptrbuf >= _lenbuf)
            {
                _ptrbuf = 0;
                try
                {
                    _lenbuf = _reader.Read(_inbuf, 0, 1024);
                }
                catch (IOException e)
                {
                    throw e;
                }
                if (_lenbuf <= 0)
                    return -1;
            }
            return _inbuf[_ptrbuf++];
        }

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

        private int Skip()
        {
            int b;
            while ((b = ReadByte()) != -1 && IsSpaceChar(b)) ;
            return b;
        }

        public int NextInt()
        {
            int num = 0, b;
            var minus = false;
            while ((b = ReadByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-')
            {
                minus = true;
                b = ReadByte();
            }

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

        public long NextLong()
        {
            long num = 0, b;
            var minus = false;
            while ((b = ReadByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-')
            {
                minus = true;
                b = ReadByte();
            }

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

        public string Next()
        {
            var b = Skip();
            var sb = new StringBuilder();
            while (!(IsSpaceChar(b)))
            {
                sb.Append((char)b);
                b = ReadByte();
            }
            return sb.ToString();
        }

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

        public int[] NIS(int n)
        {
            var arrs = new int[n];
            for (int i = 0; i < n; i++)
            {
                arrs[i] = NextInt();
            }
            return arrs;
        }

        public long[] NLS(int n)
        {
            var arrs = new long[n];
            for (int i = 0; i < n; i++)
            {
                arrs[i] = NextLong();
            }
            return arrs;
        }
    }

}