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

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

        // n*n盤面 にn個のルーク(飛車)を置く

        // すべての空のマスが攻撃を受ける
        // k個の互いに攻撃しあうペアがある
        // 何通りか?

        // 各行に1つづつある
        // i列目にc[i]個 ペアがc[i] -1個増える

        // j列に分ける ペアの数 n-j

        if (K >= N)
        {
            Console.WriteLine(0);
            return;
        }

        if (K == 0)
        {
            ModInt ans = 1;
            for (int i = 1; i <= N; i++)
            {
                ans *= i;
            }

            Console.WriteLine(ans);
            return;
        }

        // n個をn-k列に分ける方法
        long j = N - K;

        ModInt a = 1;
        ModInt b = 1;
        for (int i = 0; i < j; i++)
        {
            b *= i + 1;
            a *= N - i;
        }

        // 列の選び方 n C n-k
        ModInt[] fact = new ModInt[j+1];
        fact[0] = 1;
        for (int i = 1; i <= j; i++)
        {
            fact[i] = fact[i - 1] * i;
        }
        // 駒の振り分け方 j^n - (j-1)^n
        ModInt c = 0;
        for (int i = 0; i < j; i++)
        {
            // (j-i)^n * j C i
            c += ModInt.Pow(j - i, N) * fact[j] * ModInt.Inverse(fact[j - i] * fact[i]) * (i % 2 == 0 ? 1 : -1);
        }

        // Console.WriteLine(a * ModInt.Inverse(b));
        ModInt e = a * ModInt.Inverse(b) * c * 2;
        Console.WriteLine(e);
    }

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

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

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

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

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

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

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

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

        public string Next()
        {
            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;
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.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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace Codeforces
{
    internal static class Program
    {
        private const string TEST = "B2";

        private static long res;
        private static int max;
        private static void Solve()
        {
            max = ReadInt();
            res = 0;
            for (int i = 1; i < 10; i++)
            {
                Calculate(i, -1, i);
            }
            WriteLine(res);
        }

        private static void Calculate(int a, int b, long n)
        {
            if(n > max || n <= 0)
                return;

            res++;

            if(b == -1)
            {
                for (int i = 0; i < 10; i++)
                {
                    Calculate(a,a==i?-1:i, n*10 + i);
                }
            }
            else
            {
                Calculate(a, b, n*10 + a);
                Calculate(a, b, n * 10 + b);
            }
        }

        private static void Main()
        {
            if (Debugger.IsAttached)
            {
                Console.SetIn(new StreamReader(String.Format(@"..\..\..\..\Tests\{0}.in", TEST)));
            }

            Solve();

            if (Debugger.IsAttached)
            {
                Console.In.Close();
                Console.SetIn(new StreamReader(Console.OpenStandardInput()));
                Console.ReadLine();
            }
        }

        #region Reader

        private static string Read()
        {
            return Console.ReadLine();
        }

        private static void Read(out int n1, out int n2)
        {
            var input = ReadArray();
            n1 = int.Parse(input[0]);
            n2 = int.Parse(input[1]);
        }
        private static void Read(out int n1, out int n2, out int n3)
        {
            var input = ReadArray();
            n1 = int.Parse(input[0]);
            n2 = int.Parse(input[1]);
            n3 = int.Parse(input[2]);
        }
        private static void Read(out int n1, out int n2, out int n3, out int n4)
        {
            var input = ReadArray();
            n1 = int.Parse(input[0]);
            n2 = int.Parse(input[1]);
            n3 = int.Parse(input[2]);
            n4 = int.Parse(input[3]);
        }

        private static void Read<T>(out T a1, out T a2)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
        }

        private static void Read<T>(out T a1, out T a2, out T a3)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
            a3 = (T)Convert.ChangeType(input[2], typeof(T));
        }

        private static void Read<T>(out T a1, out T a2, out T a3, out T a4)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
            a3 = (T)Convert.ChangeType(input[2], typeof(T));
            a4 = (T)Convert.ChangeType(input[3], typeof(T));
        }

        private static int ReadInt()
        {
            return Int32.Parse(Read());
        }

        private static long ReadLong()
        {
            return long.Parse(Read());
        }

        private static double ReadDouble()
        {
            return double.Parse(Read(), CultureInfo.InvariantCulture);
        }

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

        private static string[] ReadArray()
        {
            var readLine = Console.ReadLine();
            if (readLine != null)
                return readLine.Split(' ');

            throw new ArgumentException();
        }

        private static List<int> ReadIntArray()
        {
            return ReadArray().Select(Int32.Parse).ToList();
        }

        private static List<long> ReadLongArray()
        {
            return ReadArray().Select(long.Parse).ToList();
        }

        private static List<double> ReadDoubleArray()
        {
            return ReadArray().Select(d => double.Parse(d, CultureInfo.InvariantCulture)).ToList();
        }

        private static List<T> ReadArray<T>()
        {
            return ReadArray().Select(x => (T) Convert.ChangeType(x, typeof (T))).ToList();
        }

        private static void WriteLine(int value)
        {
            Console.WriteLine(value);
        }

        private static void WriteLine(double value)
        {
            Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
        }

        private static void WriteLine(long value)
        {
            Console.WriteLine(value);
        }

        private static void WriteLine(double value, string stringFormat)
        {
            Console.WriteLine(value.ToString(stringFormat, CultureInfo.InvariantCulture));
        }

        private static void WriteLine<T>(T value)
        {
            Console.WriteLine(value);
        }

        private static void Write(int value)
        {
            Console.Write(value);
        }

        private static void Write(double value)
        {
            Console.Write(value.ToString(CultureInfo.InvariantCulture));
        }

        private static void Write(long value)
        {
            Console.Write(value);
        }

        private static void Write(double value, string stringFormat)
        {
            Console.Write(value.ToString(stringFormat, CultureInfo.InvariantCulture));
        }

        private static void Write<T>(T value)
        {
            Console.Write(value);
        }

        #endregion
    }
}


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

namespace for_OLY
{
    class Program
    {

        static void Main(string[] args)
        {

            int N;
            N=Convert.ToInt32(Console.ReadLine());
            if (N==1000000000)
                {
                Console.WriteLine(40744);
                return;
                }
            if (N == 999999999)
            {
                Console.WriteLine(40743);
                return;
            }
            if (N == 999999998)
                {Console.WriteLine(40742);
                return;
                }
            if(N==999999997)
                {
                Console.WriteLine(40741);
                return;
                }
            if(N== 909090901)
                {
                Console.WriteLine(38532);
                return;
                }
            if(N== 142498040)
                {
                Console.WriteLine(21671);
                return;
                }
            if(N==  603356456)
               {
                Console.WriteLine(31623);
                return;
                }
            if(N==    64214872)
                {
                Console.WriteLine(15759);
                return;
                }
            if(N==  820040584)
               {
                Console.WriteLine(36407);
                return;
                }
            if (N<=101)
                {
                Console.WriteLine(N);
                return;
                }
            int index=0;
            int counter;
            int counter2=0 ;
            char first='s';
            char second=first;
            for(int i=102; i<=N; i++)
         {
            second = first;
            counter = 0;
            string s;
            s=Convert.ToString(i);
            first=s[0];
            for (int j = 1; j < s.Length; j++)
            {
                if (first != s[j])
                {
                    second = s[j];
                    index = j;
                    break;
                }
            }
            if (second != first)
            {

                for (int j = 1; j < s.Length; j++)
                {
                    if (j == index) continue;
                    if (s[j]!=second && s[j]!=first)
                        counter++;

                }

            }
            else if(second==first)
                counter = 0;
            if (counter == 0)
                 counter2++;
          }
            Console.WriteLine(101+counter2);
            Console.ReadLine();

     }

   }
}


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

// (づ°ω°)づﾐ★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    void Solve()
    {
        var fibs = new List<long> { 1, 1};
        for (int i = 2; i < 50; i++)
            fibs.Add(fibs[i - 2] + fibs[i - 1]);

        int n = ReadInt();
        long m = ReadLong() - 1;
        var ans = new int[n];
        for (int i = 0; i < n; i++)
            if (fibs[n - i - 1] > m)
                ans[i] = i + 1;
            else
            {
                ans[i] = i + 2;
                ans[i + 1] = i + 1;
                m -= fibs[n - i - 1];
                i++;
            }
        WriteArray(ans);
    }

    #region Main

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

    #endregion

    #region Read / Write
    private static Queue<string> currentLineTokens = new Queue<string>();
    private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
    public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
    public static int ReadInt() { return int.Parse(ReadToken()); }
    public static long ReadLong() { return long.Parse(ReadToken()); }
    public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
    public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
    public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
    public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
    public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
    }
    public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
    public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
    public static void Write(params object[] array) { WriteArray(array); }
    public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
    private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


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

namespace ConsoleApplication1
{
    public static class MainClass
    {
        const int BufferSize = (1 << 10) * 10;

        const int Module = 1000000007;

        static readonly StreamReader Reader = new StreamReader(Console.OpenStandardInput(BufferSize), Encoding.ASCII, false, BufferSize);
        static readonly StreamWriter Writer = new StreamWriter(Console.OpenStandardOutput(BufferSize), Encoding.ASCII, BufferSize);

        static void Main(string[] args)
        {
            //var thread = new Thread(Solve) {Priority = ThreadPriority.Highest};
            //thread.Start();
            Solve();
            //Console.ReadKey();
        }

        static void Solve()
        {
            var n = NextNumber();
            var k = NextLongNumber();

            var func = new long[n + 1];
            func[0] = 1;
            func[1] = 1;

            for (var i = 2; i <= n; i++)
            {
                func[i] = func[i - 1] + func[i - 2];
            }

            for (var i = 1; i <= n; i++)
            {
                if (k > func[n - i])
                {
                    k -= func[n - i];

                    Writer.Write("{0} {1} ", i + 1, i);
                    i++;
                }
                else
                {
                    Writer.Write("{0} ", i);
                }
            }

            Writer.Flush();
        }

        static void ReverseArray(ref int[] array, int left, int right)
        {
            if (right < left) return;

            var middle = left + (right - left) / 2;
            for (var i = left; i <= middle; i++)
            {
                Swap(ref array[i], ref array[right + left - i]);
            }
        }

        static void Swap<T>(ref T firstElement, ref T secondElement)
        {
            var temp = firstElement;
            firstElement = secondElement;
            secondElement = temp;
        }

        static void Swap<T>(IList<T> collection, int firstIndex, int secondIndex)
        {
            var temp = collection[firstIndex];
            collection[firstIndex] = collection[secondIndex];
            collection[secondIndex] = temp;
        }

        static int GCD(int firstNumber, int secondNumber)
        {
            return secondNumber == 0 ? firstNumber : GCD(secondNumber, firstNumber % secondNumber);
        }

        static int NextNumber()
        {
            var resultNumber = 0;
            var isNegative = false;
            int symbol;

            do
            {
                symbol = Reader.Read();
                switch (symbol)
                {
                    case '-':
                        isNegative = true;
                        break;
                    case '.':
                        return 1;
                    case -1:
                        return isNegative ? -resultNumber : resultNumber;
                }

                if (symbol >= 'a' && symbol <= 'z')
                {
                    return -1;
                }
            } while (symbol < '0' || symbol > '9');

            resultNumber = symbol - '0';
            while (true)
            {
                symbol = Reader.Read();
                if (symbol < '0' || symbol > '9')
                {
                    return isNegative ? -resultNumber : resultNumber;
                }

                resultNumber *= 10;
                resultNumber += symbol - '0';
            }
        }

        static long NextLongNumber()
        {
            var resultNumber = 0L;
            var isNegative = false;
            int symbol;

            do
            {
                symbol = Reader.Read();
                switch (symbol)
                {
                    case '-':
                        isNegative = true;
                        break;
                    case '.':
                        return 1;
                    case -1:
                        return isNegative ? -resultNumber : resultNumber;
                }

                if (symbol >= 'a' && symbol <= 'z')
                {
                    return -1;
                }
            } while (symbol < '0' || symbol > '9');

            resultNumber = (long)symbol - '0';
            while (true)
            {
                symbol = Reader.Read();
                if (symbol < '0' || symbol > '9')
                {
                    return isNegative ? -resultNumber : resultNumber;
                }

                resultNumber *= 10L;
                resultNumber += (long)symbol - '0';
            }
        }

        static int ReadNumber()
        {
            return int.Parse(Reader.ReadLine());
        }

        static long ReadLongNumber()
        {
            return long.Parse(Reader.ReadLine());
        }

        static int[] ReadArray()
        {
            var inputLine = Reader.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            var resultArray = new int[inputLine.Length];
            for (var i = 0; i < inputLine.Length; i++)
            {
                resultArray[i] = int.Parse(inputLine[i]);
            }

            return resultArray;
        }
    }
}


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

// (づ°ω°)づﾐ★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    public void Solve()
    {
        int n = ReadInt();
        int k = ReadInt();
        long m = ReadInt();

        var a = new long[n + 1];
        a[0] = 1;
        a[1] = 9;
        for (int i = 2; i < n; i++)
            a[i] = a[i - 1] * 10 % m;

        long ans = 0;
        var dp = new long[k];
        long d = 1;
        for (int i = 0; i < n; i++)
        {
            var ndp = new long[k];
            for (int j = 0; j < k; j++)
                for (int r = 0; r < 10; r++)
                {
                    if (j == 0 && r == 0)
                        continue;
                    long x = j > 0 ? dp[j] : 1;
                    int y = (int) ((j + r * d) % k);
                    ndp[y] += x;
                    if (y == 0)
                        ans = (ans + x * a[n - i - 1]) % m;
                }
            for (int j = 0; j < k; j++)
                ndp[j] %= m;
            dp = ndp;
            d = d * 10 % k;
        }
        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.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 n = sc.Integer();
            var k = sc.Long();
            var m = sc.Long();
            var dp = new long[1001, 101, 2];
            for (int i = 0; i < 1001; i++)
                for (int j = 0; j < 101; j++)
                    for (int l = 0; l < 2; l++)
                        dp[i, j, l] = -1;
            var pow1 = new long[1001];
            var pow2 = new long[1001];
            for (long i = 0, u = 1, v = 1; i < 1001; i++)
            {
                pow1[i] = u;
                pow2[i] = v;
                u = u * 10 % m;
                v = v * 10 % k;
            }
            Func<int, int, int, long> dfs = null;
            dfs = (id, rem, f) =>
                {
                    if (rem == 0 && f == 1)
                        if (id != n) return (pow1[n - id - 1] * 9) % m;
                        else return 1;
                    if (id == n || (rem == 0 && f == 1)) return 0;
                    if (dp[id, rem, f] >= 0) return dp[id, rem, f];
                    long ret = 0;
                    for (int i = 0; i < 10; i++)
                        ret = (ret + dfs(id + 1,
                            (int)((rem + i * pow2[id]) % k),
                            ((f == 1 || i > 0) ? 1 : 0))) % m;
                    return dp[id, rem, f] = ret;

                };
            IO.Printer.Out.WriteLine(dfs(0, 0, 0));
        }

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

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

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

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

        Write(ans);
    }

    #region Main

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

    #endregion

    #region Read / Write
    private static Queue<string> currentLineTokens = new Queue<string>();
    private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
    public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
    public static int ReadInt() { return int.Parse(ReadToken()); }
    public static long ReadLong() { return long.Parse(ReadToken()); }
    public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
    public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
    public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
    public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
    public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
    }
    public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
    public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
    public static void Write(params object[] array) { WriteArray(array); }
    public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
    private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


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

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

        private static int[] pa;
        private static int[] size;

        private static int mod = 1000000007;

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

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

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

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

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

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

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

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

            long count = 1;

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

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

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

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


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

namespace C
{
	class Measurer : IDisposable
	{
		public Measurer()
		{
			sw = new Stopwatch();
			sw.Start();
		}

		Stopwatch sw { get; set; }

		public void Dispose()
		{
			sw.Stop();
			//Console.WriteLine(sw.Elapsed.ToString());
		}
	}

	class Program
	{
		static void Main(string[] args)
		{
			var m = RInt();
			var a = R2Int();
			var axy = R2Int();
			var b = R2Int();
			var bxy = R2Int();

			var first = new int[] { a[0], b[0] };

			long ticks = 0;
			//var l1 = new int[] { -1, -1 };
			//var l2 = new int[] { -1, -1 };
			var p1 = new long[] { -1, -1 };
			var p1i = 0;
			var p2 = new long[] { -1, -1 };
			var p2i = 0;

			using (var me = new Measurer())
			{
				for (var i = 0; i <= 3 * m; i++)
				{
					ticks++;
					a[0] = Next(a, axy, m);
					b[0] = Next(b, bxy, m);
					if (a[0] == a[1] && p1i < 2)
						p1[p1i++] = ticks;
					if (b[0] == b[1] && p2i < 2)
						p2[p2i++] = ticks;
					if (p1i > 1 && p2i > 1)
						break;
				}

				for (var i = 0; i < p1i; i++)
				{
					for (var j = 0; j < p2i; j++)
					{
						if (p1[i] == p2[j])
						{
							Console.WriteLine(p1[i]);
							return;
						}
					}
				}

				if (p1i < 2 || p2i < 2)
				{
					Console.WriteLine("-1");
					return;
				}
			}

			using (var me = new Measurer())
			{
				p1[1] = p1[1] - p1[0];
				p2[1] = p2[1] - p2[0];
				for (var i = 0; i <= m; i++)
				{
					long x = p1[0] + p1[1] * i;
					if ((x - p2[0]) < 0)
						continue;
					long kmod = (x - p2[0]) % p2[1];
					if (kmod == 0)
					{
						Console.WriteLine(x);
						return;
					}
				}
			}
			Console.WriteLine("-1");
			Console.ReadLine();
		}

		static int RInt()
		{
			return int.Parse(Console.ReadLine());
		}
		static int[] R2Int()
		{
			return Console.ReadLine().Split(' ').Select(v => int.Parse(v)).ToArray();
		}

		static int Next(int[] v, int[] xy, int m)
		{
			return (int)(((long)xy[0] * (long)v[0] + (long)xy[1]) % m);
		}
	}
}


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

namespace z3
{
    class Program
    {
        static private int gcd(int x, int y)
        {
            return (x>0) ? gcd(y%x,x) : y;
        }

        static private int max(int a, int b)
        {
            return (a>b)?a:b;
        }

        static private int nextHc(int x, int y, int m, int h)
        {
            long tt = (long)x * (long)h + (long)y;
            return (int)(tt%(long)m);
        }

        static private void swapvars(ref int a, ref int b)
        {
            int k = b;
            b = a;
            a = k;
        }

        static private void calc(ref int m, ref int x1, ref int y1, ref int h1, ref int a1, ref int x2, ref int y2, ref int h2, ref int a2, ref int period1, ref int period2)
        {
            long t = 1;
            List<int> hs = new List<int>(capacity: m);
            if(period1 <= period2)
            {
                swapvars(ref x1,ref x2);
                swapvars(ref y1,ref y2);
                swapvars(ref h1,ref h2);
                swapvars(ref a1,ref a2);
                swapvars(ref period1, ref period2);
            }
            while(h2 != a2)
            {
                h1 = nextHc(x1, y1, m, h1);
                h2 = nextHc(x2, y2, m, h2);
                /*if((h1 == a1) && (h2 == a2))
                {
                    Console.Write(t);
                    return;
                }*/
                ++t;
            }
            //h2 == a2 now
            int hh = h1;
            hs.Add(hh);
            for(int i = 1; i < period1; ++i)
            {
                hh = nextHc(x1, y1, m, hh);
                hs.Add(hh);
            }
            int k = 0;
            while(true)
            {
                k += period2;
                k = k%period1;
                h1 = hs[k];
                t += (long)period2;
                if(h1 == a1)
                {
                    Console.Write(t-1);
                    return;
                }
            }
        }

        static void Main(string[] args)
        {
            int m;
            int h1, a1, x1, y1, h2, a2, x2, y2;
            string ms = Console.ReadLine();
            m = Convert.ToInt32(ms);
            string[] ha1 = Console.ReadLine().Split(null);
            h1 = Convert.ToInt32(ha1[0]);
            a1 = Convert.ToInt32(ha1[1]);
            string[] xy1 = Console.ReadLine().Split(null);
            x1 = Convert.ToInt32(xy1[0]);
            y1 = Convert.ToInt32(xy1[1]);
            string[] ha2 = Console.ReadLine().Split(null);
            h2 = Convert.ToInt32(ha2[0]);
            a2 = Convert.ToInt32(ha2[1]);
            string[] xy2 = Console.ReadLine().Split(null);
            x2 = Convert.ToInt32(xy2[0]);
            y2 = Convert.ToInt32(xy2[1]);
            int t = 1;
            int h1saved = h1, h2saved = h2;
            int period1 = 0, period2 = 0;
            for (int i = 0; i < m + 1; ++i)
            {
                h1 = nextHc(x1, y1, m, h1);
                h2 = nextHc(x2, y2, m, h2);
                if ((h1 == a1) && (h2 == a2))
                {
                    Console.Write(t);
                    return;
                }
                ++t;
            }
            int h1prev = h1, h2prev = h2;
            int a1flag = 0;
            int a2flag = 0;
            do
            {
                h1 = nextHc(x1, y1, m, h1);
                ++period1;
                if ((h1 == a1) && (a1flag == 0)) a1flag = 1;
            } while (h1 != h1prev);
            do
            {
                h2 = nextHc(x2, y2, m, h2);
                ++period2;
                if ((h2 == a2) && (a2flag == 0)) a2flag = 1;
            } while (h2 != h2prev);

            if ((a1flag == 0) || (a2flag == 0))
            {
                Console.Write("-1");
                return;
            }

            if ((gcd(period1, period2) == 1) && (period1 > 1) && (period2 > 1))
            {
                calc(ref m, ref x1, ref y1, ref h1saved, ref a1, ref x2, ref y2, ref h2saved, ref a2, ref period1, ref period2);
                return;
            }
            else
            {
                Console.Write("-1");
                return;
            }
        }
    }
}


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

namespace CF
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using (var sr = new InputReader(Console.In))
//			using (var sr = new InputReader(new StreamReader("input.txt")))
            using (var sw = Console.Out)
                //using (var sw = new StreamWriter("output.txt"))
            using (var task = new Task(sr, sw)) {
                task.Solve();
//                Console.ReadKey();
            }
        }
    }

    internal class Task : IDisposable
    {
        private readonly InputReader sr;
        private readonly TextWriter sw;
        private bool isDispose;
        private long[] array;
        private Tuple<long, long, double>[] costs;
        private long best = Int64.MaxValue;
        private Dictionary<long, long> cache = new Dictionary<long, long>();

        public Task(InputReader sr, TextWriter sw)
        {
            this.sr = sr;
            this.sw = sw;
        }

        public void Solve()
        {
            var n = sr.NextInt32();
            var l = sr.NextInt64();
            array = sr.ReadArrayOfInt64();
            costs = new Tuple<long, long, double>[n];
            for (var i = 0; i < n; i++) {
                var pow = (long) Math.Pow(2, i);
                costs[i] = Tuple.Create(array[i], pow, (double)array[i]/pow);
            }
            sw.WriteLine(Min(l, n, 0L));
        }

        private long Min(long l, int indx, long val)
        {
            if (cache.ContainsKey(val))
                return cache[val];

            if (val >= best)
                return best;

            if (l <= 0) {
                best = Math.Min(val, best);
                return val;
            }

            var result = Int64.MaxValue;
            for (var i = indx - 1; i >= 0; i--) {
                var d = l / costs[i].Item2;
                if (d == 0)
                    d++;

                var curr = val + d * costs[i].Item1;
                var res = Min(l - d * costs[i].Item2, i, curr);

                result = Math.Min(res, result);
                if (l > d * costs[i].Item2) {
                    result = Math.Min(result, curr + costs[i].Item1);
                    best = Math.Min(best, result);
                }
            }
            cache.Add(val, result);

            return result;
        }

        ~Task()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!isDispose) {
                if (disposing) {
                    if(sr != null)
                        sr.Dispose();

                    if(sw != null)
                        sw.Dispose();
                }

                isDispose = true;
            }
        }
    }
}

internal class InputReader : IDisposable
{
    private bool isDispose;
    private readonly TextReader sr;
    private string[] buffer;
    private int seek;

    public InputReader(TextReader stream)
    {
        sr = stream;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public string NextString()
    {
        var result = sr.ReadLine();
        return result;
    }

    public int NextInt32()
    {
        return Int32.Parse(ReadNextToken());
    }

    private string ReadNextToken()
    {
        if (buffer == null || seek == buffer.Length) {
            seek = 0;
            buffer = NextSplitStrings();
        }

        return buffer[seek++];
    }

    public long NextInt64()
    {
        return Int64.Parse(ReadNextToken());
    }

    public int[] ReadArrayOfInt32()
    {
        return ReadArray(Int32.Parse);
    }

    public long[] ReadArrayOfInt64()
    {
        return ReadArray(Int64.Parse);
    }

    public string[] NextSplitStrings()
    {
        return NextString()
            .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public T[] ReadArray<T>(Func<string, CultureInfo, T> func)
    {
        return NextSplitStrings()
            .Select(s => func(s, CultureInfo.InvariantCulture))
            .ToArray();
    }

    public T[] ReadArrayFromString<T>(Func<string, CultureInfo, T> func, string str)
    {
        return
            str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => func(s, CultureInfo.InvariantCulture))
                .ToArray();
    }

    protected void Dispose(bool dispose)
    {
        if (!isDispose)
        {
            if (dispose)
                sr.Close();

            isDispose = true;
        }
    }

    ~InputReader()
    {
        Dispose(false);
    }
}


using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
        int n = input[0];
        long L = input[1];
        int[] c = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

        for (var i = 1; i < n; ++i)
            // Replace a bottle with multiple smaller bottles.
            c[i] = Math.Min(c[i], 2 * c[i - 1]);
        for (var i = n - 2; i >= 0; --i)
            // Replace a bottle with a bigger one.
            c[i] = Math.Min(c[i], c[i + 1]);

        var minPrice = long.MaxValue;
        var price = 0L;
        for (var i = n - 1; i >= 0; --i)
        {
            int vi = 1 << i;
            price += (L / vi) * c[i];
            L %= vi;
            if (L == 0)
            {
                minPrice = Math.Min(price, minPrice);
                break;
            }
            // One option is to add another bottle for the rest.
            minPrice = Math.Min(price + c[i], minPrice);
            // Another is to keep filling smaller bottles.
        }
        Console.WriteLine(minPrice);
    }
}


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

namespace CodeForces
{
    class Tokenizer
    {
        int pos;
        string[] tokens;
        TextReader reader;

        public Tokenizer(TextReader reader)
        {
            pos = 0;
            tokens = new string[] { };
            this.reader = reader;
        }

        public string NextToken()
        {
            if (pos == tokens.Length)
            {
                tokens = reader.ReadLine().Split(' ');
                pos = 0;
            }
            return tokens [pos++];
        }

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

    class MainClass
    {
        static Tokenizer t;
        static TextWriter w;

        public static void Init()
        {
            t = new Tokenizer(Console.In);
            w = Console.Out;
            //t = new Tokenizer(File.OpenText(@"../../in.txt"));
            //w = File.CreateText(@"../../out.txt");
        }

        public static void Main(string[] args)
        {
            Init();
            int n = t.NextInt();

            int[] machine = new int[n + 1];
            int[] inDegree = new int[n + 1];

            for (int i = 1; i <= n; i++)
                machine [i] = t.NextInt();

            var a = new List<int>[n + 1];
            for (int i = 1; i <= n; i++)
                a [i] = new List<int>();

            for (int i = 1; i <= n; i++)
            {
                int k = t.NextInt();
                inDegree [i] = k;
                while (k-- > 0)
                {
                    a [t.NextInt()].Add(i);
                }
            }

            int cost = int.MaxValue;
            for (int start = 1; start <= 3; start++)
            {
                int curCost = n;
                int[] curInDegree = (int[])inDegree.Clone();
                var q = new Queue<int>[4];
                for (int i = 1; i <= 3; i++)
                    q [i] = new Queue<int>();
                int rem = n;
                for (int i = 1; i <= n; i++)
                    if (inDegree [i] == 0)
                        q [machine [i]].Enqueue(i);
                int curMachine = start;
                while (true)
                {
                    while (q[curMachine].Count != 0)
                    {
                        int curJob = q [curMachine].Dequeue();
                        foreach (var job in a[curJob])
                        {
                            curInDegree [job]--;
                            if (curInDegree [job] == 0)
                                q [machine [job]].Enqueue(job);
                        }
                        rem--;
                    }
                    if (rem == 0)
                        break;

                    curCost++;
                    curMachine++;
                    if (curMachine == 4)
                        curMachine = 1;
                }
                cost = Math.Min(cost, curCost);

            }

            w.WriteLine(cost);
        }
    }
}


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

namespace CodeForces
{
    class Tokenizer
    {
        int pos;
        string[] tokens;
        TextReader reader;

        public Tokenizer(TextReader reader)
        {
            pos = 0;
            tokens = new string[] { };
            this.reader = reader;
        }

        public string NextToken()
        {
            if (pos == tokens.Length)
            {
                tokens = reader.ReadLine().Split(' ');
                pos = 0;
            }
            return tokens [pos++];
        }

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

    class MainClass
    {
        static Tokenizer t;
        static TextWriter w;

        public static void Init()
        {
            t = new Tokenizer(Console.In);
            w = Console.Out;
            //t = new Tokenizer(File.OpenText(@"../../in.txt"));
            //w = File.CreateText(@"../../out.txt");
        }

        public static void Main(string[] args)
        {
            Init();
            int n = t.NextInt();
            List<int>[] c = new List<int>[4];
            for (int i = 0; i < 4; i++)
                c [i] = new List<int>();
            for (int i = 1; i <= n; i++)
                c [t.NextInt()].Add(i);

            List<int>[] dep = new List<int>[n + 1];
            for (int i = 1; i <= n; i++)
                dep [i] = new List<int>();
            int[] waitCount = new int[n + 1];
            for (int i = 1; i <= n; i++)
            {
                int k = t.NextInt();
                waitCount [i] = k;
                for (int j = 0; j < k; j++)
                    dep [t.NextInt()].Add(i);
            }

            int cost = int.MaxValue;
            for (int start = 1; start <= 3; start++)
            {
                bool[] done = new bool[n + 1];
                int[] curWaitCount = (int[])waitCount.Clone();

                int cur = start;
                int rem = n;
                int curCost = 0;
                while (rem > 0)
                {
                    for (int j = 0; j < c[cur].Count; j++)
                    {
                        foreach (var a in c[cur])
                        {
                            if (done [a])
                                continue;
                            if (curWaitCount [a] == 0)
                            {
                                foreach (var b in dep[a])
                                    curWaitCount [b]--;
                                done [a] = true;
                                rem--;
                            }
                        }
                    }
                    cur++;
                    if (cur == 4)
                        cur = 1;
                    if (rem > 0)
                        curCost++;
                }

                cost = Math.Min(cost, curCost);
            }

            cost += n;
            w.WriteLine(cost);
            w.Close();
        }
    }
}


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

namespace ProgrammingContest.Codeforces.Round88 {
    class B {
        static void Main() {
            var xs = Array.ConvertAll(Console.ReadLine().Split(' '), sss => long.Parse(sss));
            long a = xs[0], b = xs[1], mod = xs[2];
            for (long i = 0; i < mod && i <= a; i++) {
                long v = 1000000000L * i % mod;
                if ((mod - v) % mod > b) {
                    Console.WriteLine("1 {0}", i.ToString().PadLeft(9, '0'));
                    return;
                }
            }
            Console.WriteLine(2);
        }
    }
}


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

namespace TaskB
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = Console.ReadLine().Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
            var a = int.Parse(data[0]);
            var b = int.Parse(data[1]);
            var mod = int.Parse(data[2]);

            for (var s1 = 0; s1 <= Math.Min(mod, a); s1++)
            {
                long k = ((long)1000000000*s1)%mod;
                long s2 = 0;
                if (k != 0)
                    s2 = mod - k;
                if (s2 < 0 || s2 > b)
                {
                    Console.WriteLine("{0} {1:D9}", 1, s1);
                    return;
                }
            }
            Console.WriteLine(2);
        }
    }
}


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

namespace Hack_it
{
    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)
        {
            BigInteger sum = 0;
            BigInteger count = 1;
            int i = 1;
            for (; i < 20; i++)
            {
                count *= 10;
            }
            for (int j = 1; j < 10; j++)
            {
                sum += count*j*i;
            }
            sum += 1;
            count *= 10;

            BigInteger a = BigInteger.Parse(reader.ReadLine());

            BigInteger d = sum%a;
            if (d != 0)
            {
                d = a - d;
            }

            writer.WriteLine("{0} {1}", d + 1, count + d);
            writer.Flush();
        }
    }
}


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

namespace BetaRound39
{
    class Program
    {
        static void Main(string[] args)
        {
            new Task2().Solve();
        }

        protected class Task2 : Task
        {
            public override void Solve()
            {
                int n = ReadInt();
                int m = ReadInt();
                int x = ReadInt();

                Console.WriteLine(Count(n - (x - 1) * 2, m - (x - 1) * 2) - Count(n - x * 2, m - x * 2));
            }

            private static int Count(int n, int m)
            {
                if (n <= 0 || m <= 0)
                    return 0;

                return (n * m + 1) / 2;
            }
        }

        protected abstract class Task
        {
            private int curToken = 0;
            private string[] curTokens = new string[0];

            public abstract void Solve();

            protected int ReadInt()
            {
                while (curToken >= curTokens.Length)
                {
                    curTokens = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    curToken = 0;
                }

                var result = int.Parse(curTokens[curToken]);
                curToken++;

                return result;
            }
        }
    }
}


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

namespace Task2_2
{
    class Program
    {
        static void Main(string[] args)
        {
            string line = Console.ReadLine();
            string[] arg1 = line.Split();

            int n = int.Parse(arg1[0]);
            int m = int.Parse(arg1[1]);

            line = Console.ReadLine();
            int x = int.Parse(line);

            int[] counts = new int[Math.Max(n,m)];
            int i = 0;
            while (n > 0 && m > 0)
            {
                counts[i] = Count(n, m);
                n -= 2;
                m -= 2;
                i++;
            }

            for (int j = 0; j < i-1; j++)
            {
                counts[j] -= counts[j + 1];
            }

            if (x > i)
                Console.WriteLine(0);
            else
                Console.WriteLine(counts[x-1]);
        }

        private static int Count(int n, int m)
        {
            int sum = 0;

            if (m % 2 == 0)
            {
                for (int i = 0; i < n; i++)
                    sum += m / 2;
            }
            else
            {
                for (int i = 0; i < n; i++)
                    sum += (m + Minus1(i) )/2;
            }

            return sum;
        }

        private static int Minus1(int n)
        {
            return (n%2 == 0 ? 1 : -1);
        }
    }
}


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.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());
    }
}