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

class Solver
{
    public void Solve(Scanner sc)
    {
        int A, B, C, D;
        sc.Make(out A, out B, out C, out D);
        var res = 0L;
        for (int z = C; z <= D; z++)
        {
            long l = Min(B, z - C);
           long r = Min(B, z - B)+1;
            res += Max(0, (Min(r, A) - l)) * (B - A + 1);
            chmax(ref l, A);
            chmax(ref r, A);
            res += (B - l) * (B - l + 1L) / 2 - (B - r) * (B - r+1) / 2;
        }
        Console.WriteLine(res);
    }
}

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

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

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

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

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

public class Program
{
    int A, B, C, D;
    public void Solve()
    {
        var sc = new Scanner();
        A = sc.NextInt();
        B = sc.NextInt();
        C = sc.NextInt();
        D = sc.NextInt();

        // a<=x<=b<=y<=c<=z<=d なx,y,zな三角形がいくつか?

        // x+y = iのやついくつか?
        var st = new LazySegmentTree<long>((l, r) => l + r, 0, (l, r) => l * r, (l, r) => l + r, 0);
        for (int x = A; x <= B; x++)
        {
            int min = x + B;
            int max = x + C;
            st.Update(min, max + 1, 1);
        }
        long ans = 0;
        for (int z = C; z <= D; z++)
        {
            // x+y > z

            ans += st.Query(z + 1, B + C + 1);
        }
        Console.WriteLine(ans);
    }

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

namespace CompLib.Collections.Generic
{
    using System;

    public class LazySegmentTree<T>
    {
        private const int N = 1 << 20;
        private readonly T[] _array;
        private readonly T[] _tmp;
        private readonly bool[] _flag;

        private readonly T _identity, _updateIdentity;
        private readonly Func<T, T, T> _operation, _update;
        private readonly Func<T, int, T> _multiplication;

        /// <summary>
        /// コンストラクタ updateIdentityで初期化
        /// </summary>
        /// <param name="operation">区間演算用の演算</param>
        /// <param name="identity">(T, operation)の単位元</param>
        /// <param name="multiplication">(T, operation)のスカラー乗算</param>
        /// <param name="update">区間更新用の演算</param>
        /// <param name="updateIdentity">(T, update)の左単位元</param>
        public LazySegmentTree(Func<T, T, T> operation, T identity, Func<T, int, T> multiplication, Func<T, T, T> update,
            T updateIdentity)
        {
            _operation = operation;
            _identity = identity;
            _multiplication = multiplication;
            _update = update;
            _updateIdentity = updateIdentity;
            _array = new T[2 * N];
            for (int i = 0; i < N; i++)
            {
                _array[i + N] = _updateIdentity;
            }

            for (int i = N - 1; i >= 1; i--)
            {
                _array[i] = _operation(_array[i * 2], _array[i * 2 + 1]);
            }

            _tmp = new T[2 * N];
            for (int i = 1; i < 2 * N; i++)
            {
                _tmp[i] = _updateIdentity;
            }

            _flag = new bool[2 * N];
        }

        private void Eval(int k, int l, int r)
        {
            if (_flag[k])
            {
                if (r - l > 1)
                {
                    _tmp[k * 2] = _update(_tmp[k * 2], _tmp[k]);
                    _flag[k * 2] = true;
                    _tmp[k * 2 + 1] = _update(_tmp[k * 2 + 1], _tmp[k]);
                    _flag[k * 2 + 1] = true;
                }

                _array[k] = _update(_array[k], _multiplication(_tmp[k], r - l));
                _tmp[k] = _updateIdentity;
                _flag[k] = false;
            }
        }

        private void Update(int left, int right, int k, int l, int r, T n)
        {
            Eval(k, l, r);
            if (r <= left || right <= l) return;
            if (left <= l && r <= right)
            {
                // 本当は _update(tmp[k], n)だけど 上でEval()したので _tmp[k]は単位元
                _tmp[k] = n;
                _flag[k] = true;
                Eval(k, l, r);
            }
            else
            {
                Update(left, right, k * 2, l, (l + r) / 2, n);
                Update(left, right, k * 2 + 1, (l + r) / 2, r, n);
                _array[k] = _operation(_array[k * 2], _array[k * 2 + 1]);
            }
        }

        /// <summary>
        /// [left, right)をupdate(A[i], n)に更新する
        /// </summary>
        /// <param name="left">右端</param>
        /// <param name="right">左端</param>
        /// <param name="n">値</param>
        public void Update(int left, int right, T n) => Update(left, right, 1, 0, N, n);

        /// <summary>
        /// A[i]をupdate(A[i] ,n)に更新する
        /// </summary>
        /// <param name="i">index</param>
        /// <param name="n">値</param>
        public void Update(int i, T n) => Update(i, i + 1, n);

        private T Query(int left, int right, int k, int l, int r)
        {
            Eval(k, l, r);
            if (r <= left || right <= l) return _identity;
            if (left <= l && r <= right) return _array[k];
            return _operation(Query(left, right, k * 2, l, (l + r) / 2), Query(left, right, k * 2 + 1, (l + r) / 2, r));
        }

        /// <summary>
        /// A[left] op A[left+1] ... A[right-1]を求める O(log N)
        /// </summary>
        /// <param name="left">左端</param>
        /// <param name="right">右端</param>
        /// <returns></returns>
        public T Query(int left, int right) => Query(left, right, 1, 0, N);

        public T this[int i]
        {
            get { return Query(i, i + 1); }
        }

        public T[] ToArray()
        {
            T[] result = new T[N];
            for (int i = 0; i < N; i++)
            {
                result[i] = this[i];
            }

            return result;
        }
    }
}

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()
        {
            while (_index >= _line.Length)
            {
                _line = Console.ReadLine().Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

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

        public string[] Array()
        {
            _line = Console.ReadLine().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;

namespace Codeforces
{
	public class C
	{
		const int N = (int)2e6;
		public static int Main()
		{
			int [] input = Console.ReadLine().Split().Select(x => Convert.ToInt32(x)).ToArray();

			long [] a = new long[N];

			int A = input[0];
			int B = input[1];
			int C = input[2];
			int D = input[3];

			for (int i = A; i <= B; ++i)
			{
				++a[i + B];
				--a[i + C + 1];
			}

			for (int i = 1; i < N; ++i)
			{
				a[i] += a[i - 1];
			}

			for (int i = 1; i < N; ++i)
			{
				a[i] += a[i - 1];
			}

			long result = 0;
			for (int i = C; i <= D; ++i)
			{
				result += a[N - 1] - a[i];
			}

			Console.WriteLine(result);

			return 0;
		}
	}
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;

namespace Program
{
    public static class CODEFORCES2
    {
        static bool SAIKI = false;
        static public int numberOfRandomCases = 0;
        static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
        {
        }
        static public void Solve()
        {
            var A = NN;
            var B = NN;
            var C = NN;
            var D = NN;
            var range = D - C + 1;
            var ans = 0L;
            for (var i = 0; i < range; i++)
            {
                var z = C + i;
                var miny = B;
                var needx = z - miny + 1;
                if (needx > B)
                {
                    var herasi = B - needx;
                    miny -= herasi;
                    needx += herasi;
                    if (miny > C)
                    {
                        continue;
                    }
                }
                var cntx = B - Max(A, needx) + 1;
                var nokoriacnt = (B - A + 1) - cntx + 1;
                var bcnt = C - miny + 1;
                var mincnt = Min(nokoriacnt, bcnt);
                var s = mincnt * (2 * cntx + mincnt - 1) / 2;
                var nokorib = bcnt - mincnt;
                var thiscnt = s + nokorib * (B - A + 1);
                ans += thiscnt;
            }
            Console.WriteLine(ans);
        }
        class Printer : StreamWriter
        {
            public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
            public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
            public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
        }
        static LIB_FastIO fastio = new LIB_FastIODebug();
        static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
        static long NN => fastio.Long();
        static double ND => fastio.Double();
        static string NS => fastio.Scan();
        static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
        static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
        static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
        static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
        static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
        static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
        static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
        static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
        static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
        static IEnumerator<uint> _xsi = _xsc();
        static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
    }
}
namespace Library {
    class LIB_FastIO
    {
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[1024];
        int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        virtual public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        virtual public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        public LIB_FastIODebug() { }
        public override string Scan() => NextString();
        public override long Long() => long.Parse(NextString());
        public override double Double() => double.Parse(NextString());
    }
}

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

namespace Codeforces.R1355.C
{
    public static class Solver
    {
        public static void Main()
        {
            using (var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false })
            {
                Solve(Console.In, sw);
            }
        }

        public static void Solve(TextReader tr, TextWriter tw)
        {
            WriteAnswer(tw, Parse(tr));
        }

        private static void WriteAnswer(TextWriter tw, long answer)
        {
            tw.WriteLine(answer);
        }

        private static long Parse(TextReader tr)
        {
            var t = tr.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
            return Calc(t[0], t[1], t[2], t[3]);
        }

        public static long Calc(long a, long b, long c, long d)
        {
            var res = 0L;

            var arr = new long[Math.Max(b + c, d) + 2];

            for (var x = a; x <= b; ++x)
            {
                ++arr[x + b];
                --arr[x + c + 1];
            }

            var s = new long[arr.Length];

            for (var x = a + b; x <= b + c; ++x)
                s[x] = arr[x] + s[x - 1];

            var pre = new long[arr.Length];
            for (var x = a + b; x < pre.Length; ++x)
                pre[x] = pre[x - 1] + s[x];

            for (var z = c; z <= d; ++z)
            {
                res += pre[b + c] - pre[z];
            }

            return res;
        }

        public static long Calc0(long a, long b, long c, long d)
        {
            var res = 0L;

            for (var x = a; x <= b; ++x)
            {
                for (var y = b; y <= c; ++y)
                {
                    for (var z = c; z <= d; ++z)
                    {
                        if (x + y > z)
                            ++res;
                    }
                }
            }

            return res;
        }
    }
}

using CodeforcesRound643Div2.Questions;
using CodeforcesRound643Div2.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeforcesRound643Div2.Questions
{
    public class QuestionC_Review : AtCoderQuestionBase
    {
        public override IEnumerable<object> Solve(TextReader inputStream)
        {
            var (a, b, c, d) = inputStream.ReadValue<int, int, int, int>();
            var xyCount = new long[1000002];
            for (int x = a; x <= b; x++)
            {
                xyCount[x + b] += 1;
                xyCount[x + c + 1] -= 1;
            }

            for (int prefixSum = 0; prefixSum < 2; prefixSum++)
            {
                for (int i = 1; i < xyCount.Length; i++)
                {
                    xyCount[i] += xyCount[i - 1];
                }
            }

            long count = 0;
            for (int z = c; z <= d; z++)
            {
                count += xyCount[xyCount.Length - 1] - xyCount[z];
            }

            yield return count;
        }
    }
}

namespace CodeforcesRound643Div2
{
    class Program
    {
        static void Main(string[] args)
        {
            IAtCoderQuestion question = new QuestionC_Review();    // 問題に合わせて書き換え
            var answers = question.Solve(Console.In);

            var writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
            Console.SetOut(writer);
            foreach (var answer in answers)
            {
                Console.WriteLine(answer);
            }
            Console.Out.Flush();
        }
    }
}

#region Base Class

namespace CodeforcesRound643Div2.Questions
{

    public interface IAtCoderQuestion
    {
        IEnumerable<object> Solve(string input);
        IEnumerable<object> Solve(TextReader inputStream);
    }

    public abstract class AtCoderQuestionBase : IAtCoderQuestion
    {
        public IEnumerable<object> Solve(string input)
        {
            var stream = new MemoryStream(Encoding.Unicode.GetBytes(input));
            var reader = new StreamReader(stream, Encoding.Unicode);

            return Solve(reader);
        }

        public abstract IEnumerable<object> Solve(TextReader inputStream);
    }
}

#endregion

#region Extensions

namespace CodeforcesRound643Div2.Extensions
{
    internal static class TextReaderExtensions
    {
        internal static int ReadInt(this TextReader reader) => int.Parse(ReadString(reader));
        internal static long ReadLong(this TextReader reader) => long.Parse(ReadString(reader));
        internal static double ReadDouble(this TextReader reader) => double.Parse(ReadString(reader));
        internal static string ReadString(this TextReader reader) => reader.ReadLine();

        internal static int[] ReadIntArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(int.Parse).ToArray();
        internal static long[] ReadLongArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(long.Parse).ToArray();
        internal static double[] ReadDoubleArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(double.Parse).ToArray();
        internal static string[] ReadStringArray(this TextReader reader, char separator = ' ') => reader.ReadLine().Split(separator);

        // Supports primitive type only.
        internal static T1 ReadValue<T1>(this TextReader reader) => (T1)Convert.ChangeType(reader.ReadLine(), typeof(T1));

        internal static (T1, T2) ReadValue<T1, T2>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            return (v1, v2);
        }

        internal static (T1, T2, T3) ReadValue<T1, T2, T3>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            return (v1, v2, v3);
        }

        internal static (T1, T2, T3, T4) ReadValue<T1, T2, T3, T4>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            return (v1, v2, v3, v4);
        }

        internal static (T1, T2, T3, T4, T5) ReadValue<T1, T2, T3, T4, T5>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            return (v1, v2, v3, v4, v5);
        }

        internal static (T1, T2, T3, T4, T5, T6) ReadValue<T1, T2, T3, T4, T5, T6>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
            return (v1, v2, v3, v4, v5, v6);
        }

        internal static (T1, T2, T3, T4, T5, T6, T7) ReadValue<T1, T2, T3, T4, T5, T6, T7>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
            var v7 = (T7)Convert.ChangeType(inputs[6], typeof(T7));
            return (v1, v2, v3, v4, v5, v6, v7);
        }
    }
}

#endregion

using CodeforcesRound643Div2.Questions;
using CodeforcesRound643Div2.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeforcesRound643Div2.Questions
{
    public class QuestionC : AtCoderQuestionBase
    {
        public override IEnumerable<object> Solve(TextReader inputStream)
        {
            var (a, b, c, d) = inputStream.ReadValue<int, int, int, int>();

            long count = 0;
            for (long x = a; x <= b; x++)
            {
                var minY = Math.Max(BoundaryBinarySearch(y => x + y > c, 0, c), b);
                var maxY = c;
                long width = maxY - minY + 1;
                if (width <= 0)
                {
                    continue;
                }

                long begin = x + minY - 1;
                long overall = (begin + begin + width - 1) * width / 2;

                long overBegin = Math.Max(x + minY - d - 1, 1);
                long overEnd = x + maxY - d - 1;

                long over = overEnd > 0 ? (overBegin + overEnd) * (overEnd - overBegin + 1) / 2 : 0;
                long withRestriction = Math.Max(overall - (c - 1) * width - over, 0);

                count += withRestriction;
            }

            yield return count;
        }
        private static int BoundaryBinarySearch(Predicate<int> predicate, int ng, int ok)
        {
            // めぐる式二分探索
            // Span.BinarySearchだとできそうでできない（lower_boundがダメ）
            while (Math.Abs(ok - ng) > 1)
            {
                int mid = (ok + ng) / 2;

                if (predicate(mid))
                {
                    ok = mid;
                }
                else
                {
                    ng = mid;
                }
            }
            return ok;
        }
    }
}

namespace CodeforcesRound643Div2
{
    class Program
    {
        static void Main(string[] args)
        {
            IAtCoderQuestion question = new QuestionC();    // 問題に合わせて書き換え
            var answers = question.Solve(Console.In);

            var writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
            Console.SetOut(writer);
            foreach (var answer in answers)
            {
                Console.WriteLine(answer);
            }
            Console.Out.Flush();
        }
    }
}

#region Base Class

namespace CodeforcesRound643Div2.Questions
{

    public interface IAtCoderQuestion
    {
        IEnumerable<object> Solve(string input);
        IEnumerable<object> Solve(TextReader inputStream);
    }

    public abstract class AtCoderQuestionBase : IAtCoderQuestion
    {
        public IEnumerable<object> Solve(string input)
        {
            var stream = new MemoryStream(Encoding.Unicode.GetBytes(input));
            var reader = new StreamReader(stream, Encoding.Unicode);

            return Solve(reader);
        }

        public abstract IEnumerable<object> Solve(TextReader inputStream);
    }
}

#endregion

#region Extensions

namespace CodeforcesRound643Div2.Extensions
{
    internal static class TextReaderExtensions
    {
        internal static int ReadInt(this TextReader reader) => int.Parse(ReadString(reader));
        internal static long ReadLong(this TextReader reader) => long.Parse(ReadString(reader));
        internal static double ReadDouble(this TextReader reader) => double.Parse(ReadString(reader));
        internal static string ReadString(this TextReader reader) => reader.ReadLine();

        internal static int[] ReadIntArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(int.Parse).ToArray();
        internal static long[] ReadLongArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(long.Parse).ToArray();
        internal static double[] ReadDoubleArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(double.Parse).ToArray();
        internal static string[] ReadStringArray(this TextReader reader, char separator = ' ') => reader.ReadLine().Split(separator);

        // Supports primitive type only.
        internal static T1 ReadValue<T1>(this TextReader reader) => (T1)Convert.ChangeType(reader.ReadLine(), typeof(T1));

        internal static (T1, T2) ReadValue<T1, T2>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            return (v1, v2);
        }

        internal static (T1, T2, T3) ReadValue<T1, T2, T3>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            return (v1, v2, v3);
        }

        internal static (T1, T2, T3, T4) ReadValue<T1, T2, T3, T4>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            return (v1, v2, v3, v4);
        }

        internal static (T1, T2, T3, T4, T5) ReadValue<T1, T2, T3, T4, T5>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            return (v1, v2, v3, v4, v5);
        }

        internal static (T1, T2, T3, T4, T5, T6) ReadValue<T1, T2, T3, T4, T5, T6>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
            return (v1, v2, v3, v4, v5, v6);
        }

        internal static (T1, T2, T3, T4, T5, T6, T7) ReadValue<T1, T2, T3, T4, T5, T6, T7>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
            var v7 = (T7)Convert.ChangeType(inputs[6], typeof(T7));
            return (v1, v2, v3, v4, v5, v6, v7);
        }
    }
}

#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;

namespace Program
{
    public static class CODEFORCES2
    {
        static bool SAIKI = false;
        static public int numberOfRandomCases = 0;
        static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
        {
        }
        static public void Solve()
        {
            var A = NN;
            var B = NN;
            var C = NN;
            var D = NN;
            var range = D - C + 1;
            var ans = 0L;
            for (var i = 0; i < range; i++)
            {
                var z = C + i;
                var miny = B;
                var needx = z - miny + 1;
                if (needx > B)
                {
                    var herasi = B - needx;
                    miny -= herasi;
                    if (miny > C)
                    {
                        continue;
                    }
                }
                var cntx = B - Max(A, needx) + 1;
                var nokoriacnt = (B - A + 1) - cntx + 1;
                var bcnt = C - B + 1;
                var mincnt = Min(nokoriacnt, bcnt);
                var s = mincnt * (2 * cntx + mincnt - 1) / 2;
                var nokorib = bcnt - mincnt;
                var thiscnt = s + nokorib * (B - A + 1);
                ans += thiscnt;
            }
            Console.WriteLine(ans);
        }
        class Printer : StreamWriter
        {
            public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
            public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
            public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
        }
        static LIB_FastIO fastio = new LIB_FastIODebug();
        static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
        static long NN => fastio.Long();
        static double ND => fastio.Double();
        static string NS => fastio.Scan();
        static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
        static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
        static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
        static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
        static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
        static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
        static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
        static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
        static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
        static IEnumerator<uint> _xsi = _xsc();
        static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
    }
}
namespace Library {
    class LIB_FastIO
    {
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[1024];
        int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        virtual public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        virtual public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        public LIB_FastIODebug() { }
        public override string Scan() => NextString();
        public override long Long() => long.Parse(NextString());
        public override double Double() => double.Parse(NextString());
    }
}

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

namespace Codeforces.R1355.C
{
    public static class Solver
    {
        public static void Main()
        {
            using (var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false })
            {
                Solve(Console.In, sw);
            }
        }

        public static void Solve(TextReader tr, TextWriter tw)
        {
            WriteAnswer(tw, Parse(tr));
        }

        private static void WriteAnswer(TextWriter tw, long answer)
        {
            tw.WriteLine(answer);
        }

        private static long Parse(TextReader tr)
        {
            var t = tr.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
            return Calc(t[0], t[1], t[2], t[3]);
        }

        public static long Calc(long a, long b, long c, long d)
        {
            var res = 0L;

            for (var x = a; x <= b; ++x)
            {
                var yMin = Math.Max(b, c + 1 - x);
                var zMax = Math.Min(d + 1, x + yMin);
                var zNum = zMax - c;

                var yNum = c + 1 - yMin;

                res += zNum * yNum;
                res += (yNum - 1) * yNum / 2;
            }

            return res;
        }
    }
}


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solution
{
    public void Solve()
    {
        int n = ReadInt();
        int mod = ReadInt();

        var dp = new long[n + 1];
        dp[1] = 1;
        long sum = 1;
        for (int i = 2; i <= n; i++)
        {
            dp[i] = sum;
            int j;
            for (j = 2; j * j <= i; j++)
                dp[i] = (dp[i] + dp[i / j]) % mod;
            int p = j - 1;
            for (j = i / j; j > 0; j--)
            {
                int o = i / j;
                dp[i] = (dp[i] + (o - p) * dp[j]) % mod;
                p = o;
            }
            sum = (sum + dp[i]) % mod;
        }

        Write(dp[n]);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUGLOCAL
        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("ysys.in");
        //writer = new StreamWriter("output.txt");
#endif
        try
        {
            new Solution().Solve();
            //var thread = new Thread(new Solution().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
        }
        catch (Exception ex)
        {
#if DEBUGLOCAL
            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 static System.Console;
using System.Linq;

class cf740
{
    static int NN => int.Parse(ReadLine());
    static int[] NList => ReadLine().Split().Select(int.Parse).ToArray();
    static void Main()
    {
        var c = NList;
        var (n, key) = (c[0], c[1]);
        var suball = 0L;
        var dp = new long[n + 1];
        dp[n] = 1;
        for (var i = n; i > 1; --i)
        {
            var val = (dp[i] + suball) % key;
            suball = (suball + val) % key;
            var last = i;
            for (var j = 2; j * j <= i; ++j)
            {
                dp[i / j] = (dp[i / j] + val) % key;
                last = i / j;
            }
            var sub = 0;
            for (var j = 1; j < last; ++j)
            {
                var mul = i - i / (j + 1) - sub;
                dp[j] = (dp[j] + val * mul) % key;
                sub += mul;
            }
        }
        WriteLine((dp[1] + suball) % key);
    }
}

using System.Diagnostics;
using System.IO;
using System.Linq;
using static System.Console;

namespace CodeForces
{
    public class Program
    {
        static void Main()
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            Solve(In, Out);
            PrintTime(stopwatch);
        }
        public static void Solve(TextReader In, TextWriter Out)
        {
            int[] input = In.ReadLine().Split().Select(str => int.Parse(str)).ToArray();
            int N = input[0], m = input[1];

            int[] f = new int[N * 2 + 1];
            f[N] = 1;
            for (long n = N - 1; n > 0; n--)
            {
                f[n] = 2 * f[n + 1] % m;
                for (int i = 2; i <= N / n; i++)
                {
                    f[n] = (f[n] + f[i * n] - f[(n + 1) * i]) % m;
                    if (f[n] < 0)
                    {
                        f[n] += m;
                    }
                }
            }
            int res = (f[1] - f[2]) % m;
            if (res < 0)
            {
                res += m;
            }

            Out.WriteLine(res);
        }

        [Conditional("DEBUG")]
        internal static void PrintTime(Stopwatch stopwatch) => WriteLine(stopwatch.Elapsed);
    }
}


using System;
using System.Linq;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using StringBuilder = System.Text.StringBuilder;
//using System.Numerics;
namespace Program
{
    public class Solver
    {
        public void Solve()
        {
            var h = sc.Integer();
            var n = sc.Long();
            long l = 1;
            long r = 1L << h;
            long count = 0;
            var goL = true;
            for (int i = 0; i < h; i++)
            {
                var m = (l + r) >> 1;
                //Debug.WriteLine(m);
                count++;
                if (n <= m)
                {
                    if (!goL)
                    {
                        count += (1L << (h - i)) - 1;
                    }
                    goL = false;
                    r = m - 1;
                }
                else
                {
                    if (goL)
                    {
                        count += (1L << (h - i)) - 1;
                    }
                    goL = true;
                    l = m + 1;
                }
            }
            IO.Printer.Out.WriteLine(count);

        }

        internal IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());
        static T[] Enumerate<T>(int n, Func<T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(); return a; }
        static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; }

    }

}

#region Ex
namespace Program.IO
{
    using System.IO;
    using System.Linq;
    public class Printer : StreamWriter
    {
        static Printer()
        {
            Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false };
        }
        public static Printer Out { get; set; }
        public override IFormatProvider FormatProvider { get { return System.Globalization.CultureInfo.InvariantCulture; } }
        public Printer(System.IO.Stream stream) : base(stream, new System.Text.UTF8Encoding(false, true)) { }
        public void Write<T>(string format, IEnumerable<T> source) { base.Write(format, source.OfType<object>().ToArray()); }
        public void WriteLine<T>(string format, IEnumerable<T> source) { base.WriteLine(format, source.OfType<object>().ToArray()); }
    }
    public class StreamScanner
    {
        public StreamScanner(Stream stream) { str = stream; }
        private readonly Stream str;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        private byte read()
        {
            if (isEof) return 0;
            if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } }
            return buf[ptr++];
        }
        public char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; }
        public char[] Char(int n) { var a = new char[n]; for (int i = 0; i < n; i++) a[i] = Char(); return a; }
        public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        public long Long()
        {
            if (isEof) return long.MinValue;
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        public int Integer() { return (isEof) ? int.MinValue : (int)Long(); }
        public double Double() { return double.Parse(Scan(), System.Globalization.CultureInfo.InvariantCulture); }
        private T[] enumerate<T>(int n, Func<T> f)
        {
            var a = new T[n];
            for (int i = 0; i < n; ++i) a[i] = f();
            return a;
        }

        public string[] Scan(int n) { return enumerate(n, Scan); }
        public double[] Double(int n) { return enumerate(n, Double); }
        public int[] Integer(int n) { return enumerate(n, Integer); }
        public long[] Long(int n) { return enumerate(n, Long); }
        public void Flush() { str.Flush(); }

    }
}
static class Ex
{
    static public string AsString(this IEnumerable<char> ie) { return new string(System.Linq.Enumerable.ToArray(ie)); }
    static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); }
    static public void Main()
    {
        var solver = new Program.Solver();
        solver.Solve();
        Program.IO.Printer.Out.Flush();
    }
}
#endregion

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

namespace ConsoleApplication1
{
    class Program
    {
        static bool l;
        static BigInteger ans, he;

        static BigInteger pow2(int t)
        {
            BigInteger res = 1;
            for (int i = 0; i < t; i++)
                res *= 2;
            return res;
        }

        static void bin(BigInteger left, BigInteger right, BigInteger go)
        {
            while (left != right)
            {
                BigInteger mid = (left + right) / 2;
                if (mid < go)
                {
                    left = mid + 1;
                    if (l)
                    {
                        ans += he;
                    }
                    else
                        ans++;
                    l = true;
                }
                else
                {
                    right = mid;
                    if (!l)
                    {
                        ans += he;
                    }
                    else
                        ans++;
                    l = false;
                }
                he /= 2;
            }
        }

        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            string[] str = s.Split();
            int h = int.Parse(str[0]);
            he = pow2(h);
            BigInteger n = BigInteger.Parse(str[1]);
            l = true;
            ans = 0;
            bin(1, he, n);
            Console.Write(ans);
        }
    }
}

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

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

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

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

            reader = iReader;
            writer = oWriter;

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

        string[] curLine;
        int curTokenIdx;

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

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

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

            return curLine[curTokenIdx++];
        }

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

        public Int64 ReadNextInt64()
        {
            return Int64.Parse(ReadNextToken());
        }

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

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

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

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

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

    class Program
    {
        protected IOHelper ioHelper;

        Int64 [,] count;
        bool[,] wayOut;

        int h;
        Int64 exit;

        public void Solve()
        {
            h = ioHelper.ReadNextInt();
            exit = ioHelper.ReadNextInt64();

            count = new Int64[h + 1, 2];
            wayOut = new bool[h + 1, 2];

            int curH=0, wayIn;

            for(wayIn = 0; wayIn< 2; wayIn++)
            {
                count[curH,wayIn] = 1;
                wayOut[curH, wayIn] = wayIn != 1;
            }

            for (curH = 1; curH <= h; curH++)
            {
                for (wayIn = 0; wayIn < 2; wayIn++)
                {
                    count[curH, wayIn] = 0;
                    bool wOut = wayOut[curH - 1, 1 - wayIn];
                    count[curH, wayIn] += count[curH - 1, 1 - wayIn];
                    int wwOut = wOut ? 1 : 0;
                    if (wwOut == wayIn)
                        wwOut = 1 - wwOut;
                    bool wOut2 = wayOut[curH - 1, 1 - wwOut];
                    count[curH, wayIn] += count[curH - 1, 1 - wwOut];

                    count[curH, wayIn]++;
                    wayOut[curH, wayIn] = wOut2;
                }
            }

            curH = h-1;
            wayIn = 0;

            Int64 result = 0;

            do
            {
                Int64 totalLeaves = (Int64)Math.Pow(2, h);
                result++;
                if (h == 0)
                    break;
                if (wayIn == 0)
                {
                    if (exit <= totalLeaves / 2)
                    {
                        wayIn = 1 - wayIn;
                    }
                    else
                    {
                        result += count[h - 1, 1 - wayIn];
                        wayIn = wayIn;
                        exit -= totalLeaves / 2;
                    }
                }
                else
                {
                    if (exit > totalLeaves / 2)
                    {
                        wayIn = 1 - wayIn;
                        exit -= totalLeaves / 2;
                    }
                    else
                    {
                        result += count[h - 1, 1 - wayIn];
                        wayIn = wayIn;
                    }
                }
                h--;
            }
            while (true);
            result--;
            ioHelper.WriteLine(result.ToString());
        }

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

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

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

namespace Guess_Your_Way_Out
{
    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)
        {
            var h = (int) Next();
            long n = Next() - 1;

            long sum = 0;

            long l = 0;
            long r = (((long) 1) << h) - 1;
            bool left = true;
            for (; h > 0; h--)
            {
                long mid = (r + l + 1)/2;

                sum++;

                if (mid > n)
                {
                    if (!left)
                    {
                        sum += (((long) 1) << h) - 1;
                    }

                    r = mid - 1;
                    left = false;
                }
                else
                {
                    if (left)
                    {
                        sum += (((long) 1) << h) - 1;
                    }

                    l = mid;
                    left = true;
                }
            }

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

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

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

// (づ°ω°)づﾐ★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    public void Solve()
    {
        int h = ReadInt();
        long n = ReadLong() - 1;
        bool left = true;
        long ans = h;
        for (; h >= 0; h--)
            if ((n >> h - 1 & 1) == 0)
            {
                if (!left)
                    ans += (1L << h) - 1;
                left = false;
            }
            else
            {
                if (left)
                    ans += (1L << h) - 1;
                left = true;
            }
        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;

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

    #endregion

    #region Read / Write

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #endregion
}

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            long[] arr = Console.ReadLine().Split(' ').Select(Int64.Parse).ToArray();
            long lvl = arr[0] + 1;
            long n = arr[1], total = 1, totallists = 0 ;
            double lists = Math.Pow(2, arr[0])/ 2, max = Math.Pow(2, arr[0]), min = 1;
            bool direction = true;
            for (int i = 1; i < lvl; i++) {
                totallists += (long)Math.Pow(2, i);
            }
                while (totallists != 0){
                    if (n <= lists && direction == false)
                    {
                        total += totallists / 2 + 1;
                        totallists = (totallists/2) - 1;
                        max = lists;
                        lists = Math.Floor((max + min)/2);
                    }
                    else if (n <= lists && direction == true) {
                        total++;
                        totallists = (totallists/2) - 1;
                        direction = !direction;
                        max = lists;
                        lists = Math.Floor((max + min) / 2);
                    }
                    else if (n > lists && direction == true)
                    {
                        total += totallists / 2 + 1;
                        totallists = (totallists/2) - 1;
                        min = lists;
                        lists = Math.Floor((max + min) / 2);
                    }
                    else if (n > lists && direction == false) {
                        total++;
                        totallists = (totallists/2) - 1;
                        direction = !direction;
                        min = lists;
                        lists = Math.Floor((max + min) / 2);
                    }

                }
                Console.WriteLine(total - 1);
                //Console.ReadKey();
        }
    }
}

#region imports
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

#endregion

namespace CodeForces
{
    class Problem
    {
        const bool IsContest = true;

        private void Solve()
        {
            var h = _.NextInt();

            var n = Convert.ToString(_.NextLong() - 1, 2).PadLeft(h, '0').ToCharArray().Select(x => x - '0').ToArray();

            long nVisited = 0;
            var nextDir = 0;
            const long long1 = 1;
            for (var level = 0; level < h; level++)
            {
                var dir = n[level];
                if (dir != nextDir)
                {
                    nVisited += long1 << (h - level);
                }
                else
                {
                    nVisited += 1;
                }
                nextDir = (dir + 1) % 2;
            }
            _.WriteLine(nVisited);
        }

        #region shit
        private readonly InOut _ = new InOut(IsContest);
        static void Main(string[] args)
        {
            var p = new Problem();
            p.Solve();
            p._.Close();
        }
    }
    class InOut
    {
        private const string InputFile = "input.txt";
        private const string OutputFile = "output.txt";
        public StreamWriter Cout { get; private set; }
        public StreamReader Cin { get; private set; }
        private void SetConsoleIo()
        {
            Cin = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
            Cout = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
        }
        private void SetFileIo(string inputFile, string outputFile) { Cin = new StreamReader(inputFile); Cout = new StreamWriter(outputFile); }
        public InOut() { SetConsoleIo(); }
        public InOut(string inputFile, string outputFile) { SetFileIo(inputFile, outputFile); }
        public InOut(bool isContest) { if (isContest) SetConsoleIo(); else SetFileIo(InputFile, OutputFile); }
        public void WriteLine(object x) { Cout.WriteLine(x); }
        public void Close() { Cin.Close(); Cout.Close(); }
        public void WriteLine(string format, params object[] args) { Cout.WriteLine(format, args); }
        private int _pos;
        private string[] _tokens;

        private string[] NextStringArray() { return Cin.ReadLine().Split(" \t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); }
        public string NextToken()
        {
            while (_tokens == null || _pos == _tokens.Length)
            {
                // ReSharper disable once PossibleNullReferenceException
                _tokens = NextStringArray();
                _pos = 0;
            }
            return _tokens[_pos++];
        }
        public int NextInt() { return int.Parse(NextToken()); }
        public long NextLong() { return long.Parse(NextToken()); }
        public double NextDouble() { return double.Parse(NextToken(), CultureInfo.InvariantCulture); }
        public int[] NextIntArray() { return NextStringArray().Select(int.Parse).ToArray(); }
        public byte[] NextByteArray() { return NextStringArray().Select(byte.Parse).ToArray(); }
        public long[] NextLongArray() { return NextStringArray().Select(long.Parse).ToArray(); }
        #endregion
    }
}

namespace topCoder
{
	using System;
	using System.Collections.Generic;

	class p3
	{
		static void Main(string[] args)
		{
			//p1 o = new p1();
			//o.foo();

			//p2 o = new p2();
			//o.foo();

			p3 o = new p3();
			o.foo();
		}
		public void foo()
		{
			string[] sp = Console.ReadLine().Split(' ');
			int h = int.Parse(sp[0]);
			Int64 n = Int64.Parse(sp[1]);

			Console.WriteLine(bar(h, n, 'L'));
		}

		private long bar(int h, Int64 n, char next)
		{
			if (h == 0)
				return 0;

			Int64 l = 1L << (h - 1);
			if (next == 'L')
			{
				if (n <= l)
				{
					return 1 + bar(h - 1, n, 'R');
				}
				else
				{
					return (1L << h) + bar(h - 1, n - l, 'L');
				}
			}
			else
			{
				if (n <= l)
				{
					return (1L << h) + bar(h - 1, n, 'R');
				}
				else
				{
					return 1 + bar(h - 1, n - l, 'L');
				}
			}
		}
	}
}

using System;

namespace Codeforces
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			string[] input = Console.ReadLine ().Split (' ');
			int h = Convert.ToInt32 (input [0]);
			ulong n = Convert.ToUInt64 (input [1]);
			int i = 0, b= 0, j = 1;
			ulong k = 0, residue = 0, branch = 0, side = 0, total = 0, leafs = 1;
			bool line = true;
			while (i < h) {
				leafs = leafs * 2;
				i += 1;
			}

			side = leafs;
			residue = n;
			i = 0;
			while (i < h) {
				side = side / 2;
				if (residue >= 2) {
					if (residue <= side) {
						if (line == true) {
							line = !line;
							total += 1;
						} else {
							b = i;
							k = 1;
							branch = 0;
							while (b < h) {
								branch += k;
								k = k * 2;
								b += 1;
							}
							total += branch + 1;
						}
					} else {
						residue = residue - side;
						if (line == false) {
							line = !line;
							total += 1;
						} else {
							b = i;
							k = 1;
							branch = 0;
							while (b < h) {
								branch += k;
								k = k * 2;
								b += 1;
							}
							total += branch + 1;
						}
					}
				} else if (residue == 0) {
					if (line == false) {
						line = !line;
						total += 1;
					} else {
						b = i;
						k = 1;
						branch = 0;
						while (b < h) {
							branch += k;
							k = k * 2;
							b += 1;
						}
						total += branch + 1;
					}
				} else {
					if (line == true) {
						line = !line;
						total += 1;
					} else {
						b = i;
						k = 1;
						branch = 0;
						while (b < h) {
							branch += k;
							k = k * 2;
							b += 1;
						}
						total += branch + 1;
					}
				}
				i += 1;
				j = j * 2;
			}

			Console.WriteLine (total);
		}
	}
}

namespace topCoder
{
	using System;
	using System.Collections.Generic;

	class p3
	{
		static void Main(string[] args)
		{
			//p1 o = new p1();
			//o.foo();

			//p2 o = new p2();
			//o.foo();

			p3 o = new p3();
			o.foo();
		}

		public void foo()
		{
			string[] sp = Console.ReadLine().Split(' ');
			int h = int.Parse(sp[0]);
			Int64 n = Int64.Parse(sp[1]);

			Console.WriteLine(bar(h, n, true));
		}

		private long bar(int h, Int64 n, bool left)
		{
			if (h == 0)
				return 0;

			Int64 l = 1L << (h - 1);
			if (left)
			{
				if (n <= l)
				{
					return 1 + bar(h - 1, n, !left);
				}
				else
				{
					return (1L << h) + bar(h - 1, n - l, left);
				}
			}
			else
			{
				if (n <= l)
				{
					return (1L << h) + bar(h - 1, n, !left);
				}
				else
				{
					return 1 + bar(h - 1, n - l, left);
				}
			}
		}
	}
}

using System;
using System.Linq;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using StringBuilder = System.Text.StringBuilder;
//using System.Numerics;
namespace Program
{
    public class Solver
    {
        public void Solve()
        {
            var h = sc.Integer();
            var n = sc.Long();
            long l = 1;
            long r = 1L << h;
            long count = 0;
            var goL = true;
            for (int i = 0; i < h; i++)
            {
                var m = (l + r) >> 1;
                //Debug.WriteLine(m);
                count++;
                if (n <= m)
                {
                    if (!goL)
                    {
                        count += 1L << (h - i) - 1;
                    }
                    goL = false;
                    r = m - 1;
                }
                else
                {
                    if (goL)
                    {
                        count += (1L << (h - i)) - 1;
                    }
                    goL = true;
                    l = m + 1;
                }
            }
            IO.Printer.Out.WriteLine(count);

        }

        internal IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());
        static T[] Enumerate<T>(int n, Func<T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(); return a; }
        static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; }

    }

}

#region Ex
namespace Program.IO
{
    using System.IO;
    using System.Linq;
    public class Printer : StreamWriter
    {
        static Printer()
        {
            Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false };
        }
        public static Printer Out { get; set; }
        public override IFormatProvider FormatProvider { get { return System.Globalization.CultureInfo.InvariantCulture; } }
        public Printer(System.IO.Stream stream) : base(stream, new System.Text.UTF8Encoding(false, true)) { }
        public void Write<T>(string format, IEnumerable<T> source) { base.Write(format, source.OfType<object>().ToArray()); }
        public void WriteLine<T>(string format, IEnumerable<T> source) { base.WriteLine(format, source.OfType<object>().ToArray()); }
    }
    public class StreamScanner
    {
        public StreamScanner(Stream stream) { str = stream; }
        private readonly Stream str;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        private byte read()
        {
            if (isEof) return 0;
            if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } }
            return buf[ptr++];
        }
        public char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; }
        public char[] Char(int n) { var a = new char[n]; for (int i = 0; i < n; i++) a[i] = Char(); return a; }
        public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        public long Long()
        {
            if (isEof) return long.MinValue;
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        public int Integer() { return (isEof) ? int.MinValue : (int)Long(); }
        public double Double() { return double.Parse(Scan(), System.Globalization.CultureInfo.InvariantCulture); }
        private T[] enumerate<T>(int n, Func<T> f)
        {
            var a = new T[n];
            for (int i = 0; i < n; ++i) a[i] = f();
            return a;
        }

        public string[] Scan(int n) { return enumerate(n, Scan); }
        public double[] Double(int n) { return enumerate(n, Double); }
        public int[] Integer(int n) { return enumerate(n, Integer); }
        public long[] Long(int n) { return enumerate(n, Long); }
        public void Flush() { str.Flush(); }

    }
}
static class Ex
{
    static public string AsString(this IEnumerable<char> ie) { return new string(System.Linq.Enumerable.ToArray(ie)); }
    static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); }
    static public void Main()
    {
        var solver = new Program.Solver();
        solver.Solve();
        Program.IO.Printer.Out.Flush();
    }
}
#endregion

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

namespace Guess_Your_Way_Out
{
    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)
        {
            var h = (int) Next();
            long n = Next() - 1;

            long sum = 0;

            long l = 0;
            long r = (((long) 1) << h) - 1;
            bool left = true;
            for (; h > 0; h--)
            {
                long mid = (r + l + 1)/2;

                sum++;

                if (mid > n)
                {
                    if (!left)
                    {
                        sum += (((long) 1) << (h - 1)) - 1;
                    }

                    r = mid-1;
                    left = false;
                }
                else
                {
                    if (left)
                    {
                        sum += (((long)1) << h) - 1;
                    }

                    l = mid;
                    left = true;
                }
            }

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

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

#region imports
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

#endregion

namespace CodeForces
{
    class Problem
    {
        const bool IsContest = true;

        private void Solve()
        {
            var h = _.NextInt();

            var n = Convert.ToString(_.NextLong() - 1, 2).PadLeft(h, '0').ToCharArray();

            //            var level = 0;
            long nVisited = 0;
            var nextDir = 0;
            const long long1 = 1;
            for (var level = 0; level < h; level++)
            {
                var dir = n[level];

                if (level == h - 1)
                {
                    switch (dir)
                    {
                        case '1':
                            nVisited += nextDir == 1 ? 1 : 2;
                            break;
                        case '0':
                            nVisited += nextDir == 1 ? 2 : 1;
                            break;
                        default:
                            Debug.Assert(false);
                            break;
                    }
                }
                else
                {
                    switch (dir)
                    {
                        case '1':
                            nVisited += long1 << (h - level);
                            nextDir = 0;
                            break;
                        case '0':
                            nVisited += 1;
                            nextDir = 1                                ;
                            break;
                        default:
                            Debug.Assert(false);
                            break;
                    }
                }
            }
            _.WriteLine(nVisited);
        }

        #region shit
        private readonly InOut _ = new InOut(IsContest);
        static void Main(string[] args)
        {
            var p = new Problem();
            p.Solve();
            p._.Close();
        }
    }
    class InOut
    {
        private const string InputFile = "input.txt";
        private const string OutputFile = "output.txt";
        public StreamWriter Cout { get; private set; }
        public StreamReader Cin { get; private set; }
        private void SetConsoleIo()
        {
            Cin = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
            Cout = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
        }
        private void SetFileIo(string inputFile, string outputFile) { Cin = new StreamReader(inputFile); Cout = new StreamWriter(outputFile); }
        public InOut() { SetConsoleIo(); }
        public InOut(string inputFile, string outputFile) { SetFileIo(inputFile, outputFile); }
        public InOut(bool isContest) { if (isContest) SetConsoleIo(); else SetFileIo(InputFile, OutputFile); }
        public void WriteLine(object x) { Cout.WriteLine(x); }
        public void Close() { Cin.Close(); Cout.Close(); }
        public void WriteLine(string format, params object[] args) { Cout.WriteLine(format, args); }
        private int _pos;
        private string[] _tokens;

        private string[] NextStringArray() { return Cin.ReadLine().Split(" \t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); }
        public string NextToken()
        {
            while (_tokens == null || _pos == _tokens.Length)
            {
                // ReSharper disable once PossibleNullReferenceException
                _tokens = NextStringArray();
                _pos = 0;
            }
            return _tokens[_pos++];
        }
        public int NextInt() { return int.Parse(NextToken()); }
        public long NextLong() { return long.Parse(NextToken()); }
        public double NextDouble() { return double.Parse(NextToken(), CultureInfo.InvariantCulture); }
        public int[] NextIntArray() { return NextStringArray().Select(int.Parse).ToArray(); }
        public byte[] NextByteArray() { return NextStringArray().Select(byte.Parse).ToArray(); }
        public long[] NextLongArray() { return NextStringArray().Select(long.Parse).ToArray(); }
        #endregion
    }
}