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

namespace cf_82_div2
{

    class Program
    {
        private static HashSet<int> delims =
            new HashSet<int> { (int)' ', (int)'\t', (int)'\n', (int)'\r' };
        private static StringBuilder token = new StringBuilder();

        private static void Skip()
        {
            while (delims.Contains(Console.In.Peek()))
                Console.Read();
        }

        public static bool EndOfStream()
        {
            Skip();
            return Console.In.Peek() == -1;
        }

        public static string Read()
        {
            Skip();
            int c = Console.Read();
            while (c != -1 && !delims.Contains(c))
            {
                token.Append((char)c);
                c = Console.Read();
            }
            string ret = token.ToString();
            token.Length = 0;
            return ret;
        }

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

        public static double ReadDouble()
        {
            return double.Parse(Read());
        }

        public static bool solve()
        {
            int[][] dp;
            int[] cnt, cost, weight;
            int n, W, a, b, c;
            W = ReadInt();
            n = ReadInt();
            n++;

            cnt = new int[n];
            cost = new int[n];
            weight = new int[n];
            dp = new int[2][];
            for (int i = 0; i < 2; i++)
                dp[i] = new int[W + 1];

            c = ReadInt();
            weight[0] = c;
            cost[0] = ReadInt();
            cnt[0] = W / c;
            for (int i = 1; i < n; i++)
            {
                a = ReadInt();
                b = ReadInt();
                c = ReadInt();
                cost[i] = ReadInt();
                cnt[i] = System.Math.Min(a / b, W / c);
                weight[i] = c;
            }

            for (int i = 0; i < n; i++)
            {
                for (int it = 0; it < cnt[i]; it++)
                {
                    for (int w = 0; w + weight[i] <= W; w++)
                    {
                        dp[1][w + weight[i]] = System.Math.Max(dp[1][w + weight[i]], dp[0][w] + cost[i]);
                    }
                    System.Array.Copy(dp[1], dp[0], dp[1].Length);
                }
            }

            int ans = 0;
            for (int i = 0; i <= W; i++)
                ans = System.Math.Max(ans, dp[0][i]);
            Console.WriteLine(ans);
            return false;
        }

        static void Main(string[] args)
        {
            //StreamReader reader = new StreamReader("input.txt");
            //StreamWriter writer = new StreamWriter("output.txt");
            //Console.SetIn(reader);
            //Console.SetOut(writer);
            while (solve() == true);
        }
    }
}


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

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

        public class Truple
        {
            public int a;
            public int b;
            public int c;
        }

        private void Go()
        {
            int n = GetInt();
            int m = GetInt();
            int k = GetInt();
            List<Truple>[] data = new List<Truple>[n];
            for (int i = 0; i < n; i++)
            {
                GetString();
                data[i] = new List<Truple>();
                for (int j = 0; j < m; j++)
                {
                    Truple tr;
                    data[i].Add(tr = new Truple());
                    tr.a = GetInt();
                    tr.b = GetInt();
                    tr.c = GetInt();
                }
            }
            int max = 0;
            Tuple<int, int>[] unitProfit = new Tuple<int, int>[m];
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    var buy = data[i];
                    var sell = data[j];
                    for (int x = 0; x < m; x++)
                    {
                        unitProfit[x] = new Tuple<int, int>(sell[x].b - buy[x].a, x);
                    }
                    Array.Sort(unitProfit);
                    Array.Reverse(unitProfit);
                    int kk = k;
                    int localProfit = 0;
                    for (int y = 0; y < m && kk > 0 && unitProfit[y].Item1 > 0; y++)
                    {
                        int cap = buy[unitProfit[y].Item2].c;
                        localProfit += Math.Min(cap, kk) * unitProfit[y].Item1;
                        kk -= cap;
                    }

                    if (localProfit > max) max = localProfit;
                }
            }

            Wl(max);
        }

        #region Template

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

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

            return ioEnum.Current;
        }

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

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

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

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

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

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

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

        public struct Tuple<T, K> : IComparable<Tuple<T, K>>
            where T : IComparable<T>
            where K : IComparable<K>
        {
            public T Item1;
            public K Item2;

            public Tuple(T t, K k)
            {
                Item1 = t;
                Item2 = k;
            }

            public override bool Equals(object obj)
            {
                var o = (Tuple<T, K>)obj;
                return o.Item1.Equals(Item1) && o.Item2.Equals(Item2);
            }

            public override int GetHashCode()
            {
                return Item1.GetHashCode() ^ Item2.GetHashCode();
            }

            public override string ToString()
            {
                return "(" + Item1 + " " + Item2 + ")";
            }

            #region IComparable<Tuple<T,K>> Members

            public int CompareTo(Tuple<T, K> other)
            {
                int ret = Item1.CompareTo(other.Item1);
                if (ret != 0) return ret;
                return Item2.CompareTo(other.Item2);
            }

            #endregion
        }

        #endregion
    }
}


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

namespace Task
{

    #region MyIo

    internal class MyIo : IDisposable
    {
        private readonly TextReader inputStream;
        private readonly TextWriter outputStream = Console.Out;

        private string[] tokens;
        private int pointer;

        public MyIo()
#if  LOCAL_TEST
            : this(new StreamReader("input.txt"))
#else
            : this(System.Console.In)
#endif
        {

        }

        public MyIo(TextReader inputStream)
        {
            this.inputStream = inputStream;
        }

        public char NextChar()
        {
            try
            {
                return (char)inputStream.Read();
            }
            catch (IOException)
            {
                return '\0';
            }
        }

        public string NextLine()
        {
            try
            {
                return inputStream.ReadLine();
            }
            catch (IOException)
            {
                return null;
            }
        }

        public string NextString()
        {
            try
            {
                while (tokens == null || pointer >= tokens.Length)
                {
                    tokens = (NextLine() + string.Empty).Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    pointer = 0;
                }
                return tokens[pointer++];
            }
            catch (IOException)
            {
                return null;
            }
        }

        public int NextInt()
        {
            return Next<int>();
        }

        public long NextLong()
        {
            return Next<long>();
        }

        public T Next<T>()
        {
            var t = typeof(T);

            if (t == typeof(char))
                return (T)(object)NextChar();

            object s = NextString();

            if (t == typeof(string))
                return (T)s;

            return (T)Convert.ChangeType(s, typeof(T));
        }

        public IEnumerable<T> NextWhile<T>(Predicate<T> pred)
        {
            if (pred == null)
                yield break;

            T res = Next<T>();

            while (pred(res))
            {
                yield return res;

                res = Next<T>();
            }
        }

        public IEnumerable<T> NextSeq<T>(long n)
        {
            for (var i = 0; i < n; i++)
                yield return Next<T>();
        }

        public void Print(string format, params object[] args)
        {
            outputStream.Write(string.Format(CultureInfo.InvariantCulture, format, args));
        }

        public void PrintLine(string format, params object[] args)
        {
            Print(format, args);

            outputStream.WriteLine();
        }

        public void Print(bool o)
        {
            Print(o ? "YES" : "NO");
        }

        public void PrintLine(bool o)
        {
            PrintLine(o ? "YES" : "NO");
        }

        public void Print<T>(T o)
        {
            outputStream.Write(Convert.ToString(o, CultureInfo.InvariantCulture));
        }

        public void PrintLine<T>(T o)
        {
            Print(o);

            outputStream.WriteLine();
        }

        public void Close()
        {
            inputStream.Close();
            outputStream.Close();
        }

        void IDisposable.Dispose()
        {
            Close();

#if  LOCAL_TEST
            Console.ReadLine();
#endif
        }
    }

    public static class ListExtensions
    {

        public static IEnumerable<T> ToCycleEnumerable<T>(this IEnumerable<T> self)
        {
            if (self != null)
            {
                for (; ; )
                {
                    foreach (var x in self)
                        yield return x;
                }
            }
        }

        public static T CycleGet<T>(this IList<T> self, int index)
        {
            var c = self.Count;
            return self[(index % c + c) % c];
        }

        public static IList<T> Shuffle<T>(this IList<T> self)
        {
            var rnd = new Random(DateTime.Now.Millisecond);

            var n = self.Count;

            while (n > 1)
            {
                n--;
                var k = rnd.Next(n + 1);
                var value = self[k];
                self[k] = self[n];
                self[n] = value;
            }

            return self;
        }

        public static IList<IList<T>> UseForNew2D<T>(this T def, int fd, int sd)
        {
            var fdim = new T[fd][];

            for (int i = 0; i < fd; i++)
            {
                fdim[i] = new T[sd];
                Fill(fdim[i], def);
            }

            return fdim;
        }

        public static IList<T> Fill<T>(this IList<T> self, Func<T> fval)
        {
            for (var i = 0; i < self.Count; i++)
                self[i] = fval();

            return self;
        }

        public static IList<T> Fill<T>(this IList<T> self, T val)
        {
            return self.Fill(() => val);
        }

        public static long Hash<T>(this IList<T> self, Func<T, long> val = null)
        {
            return val != null ? self.Hash((t, current) => unchecked(current * 19L + val(t))) : self.Hash(HashOne);
        }

        public static long Hash<T>(this IList<T> self, Func<T, long, long> val)
        {
            return self.Aggregate(0L, (current, t) => unchecked(val(t, current)));
        }

        public static long HashOne<T>(this T self, long current)
        {
            return unchecked(current * 19L + (Equals(self, default(T)) ? 0 : self.GetHashCode()));
        }

    }

    public static class P
    {
        public static P<T1, T2> Create<T1, T2>(T1 key, T2 val)
        {
            return new P<T1, T2>(key, val);
        }
    }

    public class P<T1, T2>
    {
        private class PComparer : IComparer<P<T1, T2>>
        {
            private readonly bool? byKey;

            public PComparer(bool? byKey)
            {
                this.byKey = byKey;
            }

            public int Compare(P<T1, T2> x, P<T1, T2> y)
            {
                x = x ?? new P<T1, T2>();
                y = y ?? new P<T1, T2>();

                if (byKey == true)
                    return Comparer<T1>.Default.Compare(x.Key, y.Key);
                else if (byKey == false)
                    return Comparer<T2>.Default.Compare(x.Value, y.Value);
                else
                {
                    var tr = Comparer<T1>.Default.Compare(x.Key, y.Key);

                    if (tr != 0)
                        tr = Comparer<T2>.Default.Compare(x.Value, y.Value);

                    return tr;
                }
            }
        }

        public P()
        {
        }

        public P(T1 key, T2 val)
        {
            this.Key = key;
            this.Value = val;
        }

        public T1 Key
        {
            get;
            set;
        }

        public T2 Value
        {
            get;
            set;
        }

        public P<T1, T2> Clone()
        {
            return new P<T1, T2>(Key, Value);
        }

        public static IComparer<P<T1, T2>> KeyComparer
        {
            get { return new PComparer(true); }
        }

        public static IComparer<P<T1, T2>> ValueComparer
        {
            get { return new PComparer(false); }
        }

        public static implicit operator T1(P<T1, T2> obj)
        {
            return obj.Key;
        }

        public static implicit operator T2(P<T1, T2> obj)
        {
            return obj.Value;
        }

        public P<T1, T2> SetKey(T1 key)
        {
            Key = key;
            return this;
        }

        public P<T1, T2> SetValue(T2 value)
        {
            Value = value;
            return this;
        }

        public override string ToString()
        {
            return string.Format("Key: {0}, Value: {1}", Key, Value);
        }

        public override int GetHashCode()
        {
            int hash = 17;
            hash = hash * 31 + ((Equals(Key, default(T1))) ? 0 : Key.GetHashCode());
            hash = hash * 31 + ((Equals(Value, default(T1))) ? 0 : Key.GetHashCode());
            return hash;

        }
    }

    #endregion

    internal class Program
    {
        #region Program

        private readonly MyIo io;

        public Program(MyIo io)
        {
            this.io = io;
        }

        public static void Main(string[] args)
        {
            using (MyIo io = new MyIo())
            {
                new Program(io)
                    .Solve();
            }
        }

        #endregion
        public const long MOD = 1000000007;
        public const double EPS = 1e-14;

        private void Solve()
        {
            var n = io.NextInt();
            var m = io.NextInt();
            var k = io.NextInt();

            var a = new int[n * m];
            var b = new int[n * m];
            var c = new int[n * m];

            for (int i = 0; i < n; i++)
            {
                var nm = io.NextLine();

                for (int j = 0; j < m; j++)
                {
                    a[j + m * i] = io.NextInt();
                    b[j + m * i] = io.NextInt();
                    c[j + m * i] = io.NextInt();
                }
            }

            var res = 0;

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (i != j)
                    {
                        var xk = k;

                        var pres = 0;

                        var sort = Enumerable.Range(0, m).OrderByDescending(x => b[j * m + x] - a[i * m + x]).ToArray();

                        foreach (var x in sort)
                        {
                            var d = (b[j * m + x] - a[i * m + x]);
                            if (d <= 0)
                                continue;

                            var tc = Math.Min(c[i * m + x], xk);

                            pres += d * tc;

                            xk -= tc;
                        }

                        res = Math.Max(res, pres);
                    }
                }
            }
            io.PrintLine(res);
        }
    }

}


//#define LOCAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _258_E
{
    class Program
    {
        class Files
        {
            StreamReader fin = new StreamReader("d:\\date.in");
            StreamWriter fout = new StreamWriter("d:\\date.out");
            public string ReadLine()
            {
                return fin.ReadLine();
            }
            public void Write(string s)
            {
                fout.Write(s);
            }
            public void WriteLine(string s)
            {
                fout.WriteLine(s);
            }
            public void Close()
            {
                fout.Close();
            }
        }
        #if LOCAL
            static Files Console = new Files();
        #endif
        const Int64 Mod = (Int64)1e9+7;
        static string[] s;
        static string Line;
        static int step = 0, Length = 0;
        static Int64 GetNext()
        {
            if (step == Length)
            {
                Line = Console.ReadLine();
                s = Line.Split(' ');
                Length = s.Length;
                step = 0;
            }
            ++step;
            return Int64.Parse(s[step - 1]);
        }
        static Int64[] a = new Int64[30];
        static Int64 Inv = 1;
        static Int64 Comb(Int64 n, Int64 k)
        {
            if (n < k)
                return 0;
            Int64 result = 1;
            for (Int64 i = n - k + 1; i <= n; ++i)
                result = (Int64)result*(i%Mod)%Mod;
            result = (Int64)result*Inv%Mod;
            return result;
        }
        static Int64 Fix(Int64 x)
        {
            Int64 ret = x;
            while(ret >= Mod)
                ret -= Mod;
            while(ret < 0)
                ret += Mod;
            return ret;
        }

        static Int64 Pow_Log(Int64 x,Int64 p)
        {
            if (p == 0)
                return 1;
            Int64 y;
            if(p%2==1)
               y = (Int64)Pow_Log(x,p-1)*x%Mod;
            else
            {
                y = Pow_Log(x,p/2);
                y = (Int64)y*y%Mod;
            }
            return y;
        }
        static void Main(string[] args)
        {
            Int64 n = GetNext(), S = GetNext(), sum = 0, Max = 1;
            Inv = 1;
            for (int i = 0; i < n; ++i)
            {
                Max *= 2;
                if (i > 0)
                    Inv *= i;
                a[i] = GetNext();
                sum += a[i];
            }
            if (sum < S)
            {
                Console.WriteLine("0");
                return;
            }

            //Console.WriteLine(Inv.ToString());
            Inv = Pow_Log(Inv%Mod, Mod - 2);

            //Console.WriteLine(Inv.ToString());
            Int64 Solution = Comb(S + n - 1, n - 1),cnt = 0;
            for (int i = 1; i < Max; ++i)
            {
                Int64 k = 0;
                int nr = 0;
                for (int j = 0; j < n; ++j)
                    if (((1 << j) & i) != 0)
                    {
                        ++nr;
                        k += a[j]+1;
                    }
                k = S - k;
                if (nr % 2 == 1)
                    cnt += Comb(k + n - 1, n - 1);
                else
                    cnt -= Comb(k + n - 1, n - 1);
                cnt = Fix(cnt);
            }
            Solution -= cnt;
            Solution = Fix(Solution);
            Console.WriteLine(Solution.ToString());
            #if LOCAL
                Console.Close();
            #endif
        }
    }
}


using System;

namespace Problem51Nod
{
    class Program
    {
        public static void Main(String[] args)
        {
            string[] input = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(input[0]);
            long sum = Convert.ToInt64(input[1]);
            input = Console.ReadLine().Split(' ');
            long[] nums = new long[n];
            for (int i = 0; i < n; i++)
                nums[i] = Convert.ToInt64(input[i]);

            Console.WriteLine(Cal(sum, nums));
        }

        static long Mod = 1000000007;
        static long[] Nums, InvFacts;

        static void Init(long[] nums)
        {
            long[] invs = new long[30];
            InvFacts = new long[30];
            invs[1] = InvFacts[1] = 1;

            for (int i = 2; i < invs.Length; i++)
            {
                invs[i] = (Mod - Mod / i * invs[Mod % i] % Mod) % Mod;
                InvFacts[i] = InvFacts[i - 1] * invs[i] % Mod;
            }

            Nums = new long[nums.Length];

            for (int i = 0; i < nums.Length; i++)
                Nums[i] = nums[i] + 1;

            Array.Sort(Nums, (a, b) => b.CompareTo(a));
        }

        static long Cal(long sum, long[] nums)
        {
            if (nums.Length == 1) return nums[0] < sum ? 0 : 1;
            Init(nums);
            return (Cal(Nums.Length - 1, sum) + Mod) % Mod;
        }

        static long Cal(int index, long sum)
        {
            int k = Nums.Length - 1;
            long result = Cmn(sum + k, k);

            for(int i = index; i >= 0 && Nums[i] <= sum; i--)
                result -= Cal(i - 1, sum - Nums[i]);

            return result % Mod;
        }

        static long Cmn(long m, long n)
        {
            long result = 1;

            for(long i = m - n + 1; i <= m; i++)
                result = i % Mod * result % Mod;

            result = result * InvFacts[n] % Mod;
            return result;
        }
    }
}


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

public class Program
{

    BinomialCoefficient C;
    public void Solve()
    {
        C = new BinomialCoefficient(500000);

        var sc = new Scanner();
#if !DEBUG
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
#endif
        int t = sc.NextInt();
        for (int i = 0; i < t; i++)
        {
            Q(sc);
        }
        Console.Out.Flush();
    }

    void Q(Scanner sc)
    {
        int n = sc.NextInt();
        int k = sc.NextInt();

        var dp = new ModInt[k + 1, 2];
        dp[0, 0] = 1;
        ModInt t1 = 0;
        for (int i = 0; i < n; i += 2)
        {
            t1 += C[n, i];
        }
        for (int i = 0; i < k; i++)
        {
            //
            {
                // j=0
                // 全部1
                // and側 1
                // xor側 n%2
                if (n % 2 == 0)
                {
                    dp[i + 1, 1] += dp[i, 0];
                }
                else
                {
                    dp[i + 1, 0] += dp[i, 0];
                }

                // 1じゃないやつある
                // and側0
                // xor側 1の個数偶数
                //
                dp[i + 1, 0] += dp[i, 0] * t1;
            }
            {
                // j =1
                dp[i + 1, 1] += dp[i, 1] * ModInt.Pow(2, n);
            }
        }

        Console.WriteLine(dp[k, 0] + dp[k, 1]);
    }

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

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.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Library;

namespace Program
{
    public static class ProblemC
    {
        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 t = NN;
            for (var i = 0; i < t; ++i)
            {
                var n = NN;
                var k = NN;
                if (n % 2 == 1)
                {
                    LIB_Mod1000000007 ans = 0;
                    LIB_Mod1000000007 evenpat = 0;
                    for (var j = 0; j < n; j += 2)
                    {
                        evenpat += LIB_Mod1000000007.Comb(n, j);
                    }
                    for (var j = 0; j <= k; ++j)
                    {
                        ans += LIB_Mod1000000007.Comb(k, j) * LIB_Mod1000000007.Pow(evenpat, k - j);
                    }
                    Console.WriteLine(ans);
                }
                else
                {
                    LIB_Mod1000000007 ans = 0;
                    LIB_Mod1000000007 evenpat = 0;
                    LIB_Mod1000000007 allpat = LIB_Mod1000000007.Pow(2, n);
                    for (var j = 0; j < n; j += 2)
                    {
                        evenpat += LIB_Mod1000000007.Comb(n, j);
                    }
                    for (var j = 0; j <= k; ++j)
                    {
                        ans += LIB_Mod1000000007.Pow(evenpat, j) * LIB_Mod1000000007.Pow(allpat, Max(0,k - j - 1));
                    }
                    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 string Join<T>(this IEnumerable<T> x, string separator = "") => string.Join(separator, x);
        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; } }
        static bool Chmax<T>(this ref T lhs, T rhs) where T : struct, IComparable<T> { if (lhs.CompareTo(rhs) < 0) { lhs = rhs; return true; } return false; }
        static bool Chmin<T>(this ref T lhs, T rhs) where T : struct, IComparable<T> { if (lhs.CompareTo(rhs) > 0) { lhs = rhs; return true; } return false; }
        static void Fill<T>(this T[] array, T value) => array.AsSpan().Fill(value);
        static void Fill<T>(this T[,] array, T value) => MemoryMarshal.CreateSpan(ref array[0, 0], array.Length).Fill(value);
        static void Fill<T>(this T[,,] array, T value) => MemoryMarshal.CreateSpan(ref array[0, 0, 0], array.Length).Fill(value);
        static void Fill<T>(this T[,,,] array, T value) => MemoryMarshal.CreateSpan(ref array[0, 0, 0, 0], array.Length).Fill(value);
    }
}
namespace Library {
    partial struct LIB_Mod1000000007 : IEquatable<LIB_Mod1000000007>, IEquatable<long>
    {
        const int _mod = 1000000007; long v;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_Mod1000000007(long x)
        {
            if (x < _mod && x >= 0) v = x;
            else if ((v = x % _mod) < 0) v += _mod;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public implicit operator LIB_Mod1000000007(long x) => new LIB_Mod1000000007(x);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public implicit operator long(LIB_Mod1000000007 x) => x.v;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Add(LIB_Mod1000000007 x) { if ((v += x.v) >= _mod) v -= _mod; }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Sub(LIB_Mod1000000007 x) { if ((v -= x.v) < 0) v += _mod; }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Mul(LIB_Mod1000000007 x) => v = (v * x.v) % _mod;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Div(LIB_Mod1000000007 x) => v = (v * Inverse(x.v)) % _mod;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 operator +(LIB_Mod1000000007 x, LIB_Mod1000000007 y) { var t = x.v + y.v; return t >= _mod ? new LIB_Mod1000000007 { v = t - _mod } : new LIB_Mod1000000007 { v = t }; }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 operator -(LIB_Mod1000000007 x, LIB_Mod1000000007 y) { var t = x.v - y.v; return t < 0 ? new LIB_Mod1000000007 { v = t + _mod } : new LIB_Mod1000000007 { v = t }; }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 operator *(LIB_Mod1000000007 x, LIB_Mod1000000007 y) => x.v * y.v;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 operator /(LIB_Mod1000000007 x, LIB_Mod1000000007 y) => x.v * Inverse(y.v);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public bool operator ==(LIB_Mod1000000007 x, LIB_Mod1000000007 y) => x.v == y.v;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public bool operator !=(LIB_Mod1000000007 x, LIB_Mod1000000007 y) => x.v != y.v;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public long Inverse(long x)
        {
            long b = _mod, r = 1, u = 0, t = 0;
            while (b > 0)
            {
                var q = x / b;
                t = u;
                u = r - q * u;
                r = t;
                t = b;
                b = x - q * b;
                x = t;
            }
            return r < 0 ? r + _mod : r;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(LIB_Mod1000000007 x) => v == x.v;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(long x) => v == x;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override bool Equals(object x) => x == null ? false : Equals((LIB_Mod1000000007)x);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override int GetHashCode() => v.GetHashCode();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override string ToString() => v.ToString();
        static List<LIB_Mod1000000007> _fact = new List<LIB_Mod1000000007>() { 1, 1 };
        static List<LIB_Mod1000000007> _inv = new List<LIB_Mod1000000007>() { 0, 1 };
        static List<LIB_Mod1000000007> _factinv = new List<LIB_Mod1000000007>() { 1, 1 };
        static long _factm = _mod;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static void B(long n)
        {
            if (_factm != _mod)
            {
                _fact = new List<LIB_Mod1000000007>() { 1, 1 };
                _inv = new List<LIB_Mod1000000007>() { 0, 1 };
                _factinv = new List<LIB_Mod1000000007>() { 1, 1 };
            }
            if (n >= _fact.Count)
            {
                for (int i = _fact.Count; i <= n; ++i)
                {
                    _fact.Add(_fact[i - 1] * i);
                    _inv.Add(_mod - _inv[(int)(_mod % i)] * (_mod / i));
                    _factinv.Add(_factinv[i - 1] * _inv[i]);
                }
            }
            _factm = _mod;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 Comb(long n, long k)
        {
            B(n);
            if (n == 0 && k == 0) return 1;
            if (n < k || n < 0) return 0;
            return _fact[(int)n] * _factinv[(int)(n - k)] * _factinv[(int)k];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 CombOK(long n, long k)
        {
            LIB_Mod1000000007 ret = 1;
            for (var i = 0; i < k; i++) ret *= n - i;
            for (var i = 1; i <= k; i++) ret /= i;
            return ret;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 Perm(long n, long k)
        {
            B(n);
            if (n == 0 && k == 0) return 1;
            if (n < k || n < 0) return 0;
            return _fact[(int)n] * _factinv[(int)(n - k)];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 KanzenPerm(long n, long k) => Enumerable.Range(0, (int)k + 1).Aggregate((LIB_Mod1000000007)0, (a, e) => a + (1 - ((e & 1) << 1)) * LIB_Mod1000000007.Comb(k, e) * LIB_Mod1000000007.Perm(n - e, k - e));
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static public LIB_Mod1000000007 Pow(LIB_Mod1000000007 x, long y)
        {
            LIB_Mod1000000007 a = 1;
            while (y != 0)
            {
                if ((y & 1) == 1) a.Mul(x);
                x.Mul(x);
                y >>= 1;
            }
            return a;
        }
    }
    class LIB_FastIO
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[2048];
        int len, ptr;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        byte read()
        {
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 2048)) <= 0)
                {
                    return 0;
                }
            }
            return buf[ptr++];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        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();
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        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 << 3) + (ret << 1) + b - '0';
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIODebug() { }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override string Scan() => NextString();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override long Long() => long.Parse(NextString());
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override double Double() => double.Parse(NextString());
    }
}


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

namespace CodeForces {
    struct Node {
        public int X, Y, D;
        public Node(int x,int y, int d) {
            X = x;
            Y = y;
            D = d;
        }
    }

    class Pair : IComparable<Pair> {
        public int First, Second;
        public Pair(int f, int s) {
            First = f;
            Second = s;
        }

        public int CompareTo(Pair other) {
            return other.Second.CompareTo(Second);
        }
    }

    class Desc : IComparer<int> {
        public int Compare(int x, int y) {
            return y.CompareTo(x);
        }
    }

    class Cf {
        static TextReader input;
        static void Main(string[] args) {
#if TESTS
            Stopwatch sw = new Stopwatch();
            sw.Start();
            input = new StreamReader("input.txt");
#else
            input = Console.In;
#endif
            Solve();
#if TESTS
            Console.WriteLine();
            Console.WriteLine("Milliseconds: {0}", sw.ElapsedMilliseconds);
            Console.ReadLine();
#endif
        }

        const int MOD = 1000000007;
        static int n, m;
        static void Solve() {
            n = nextInt();
            if (n == 1) {
                Console.WriteLine(1);
                return;
            }
            if (n == 2) {
                Console.WriteLine(3);
                return;
            }
            if (n == 3) {
                Console.WriteLine(5);
                return;
            }
            if ((n & 1) == 1)
                --n;
            int cnt = n;
            int[] c = new int[100];
            c[0] = 4;
            for (int i = 1; i < 100; i++) {
                c[i] = 4 * (i + 1) + c[i - 1];
            }
            int pos = Array.BinarySearch(c, n);
            if (pos >= 0) {
                Console.WriteLine(2 * (pos + 1) + 1);
                return;
            }
            for (int i = 1; i < 100; i++) {
                if (n > c[i - 1] && n < c[i]) {
                    Console.WriteLine(2 * (i + 1) + 1);
                    return;
                }
            }
        }

        #region math
        static long gcd(long a, long b) {
            return b != 0 ? gcd(b, a % b) : a;
        }

        static long lcm(long a, long b) {
            return a / gcd(a, b) * b;
        }

        //static int SquaredDistanceBetweenSegments(int x1, int y1, int x2, int y2, int xx1, int yy1, int xx2, int yy2) {
        //    return Math.Min(Math.Min(SquaredDistanceToSegment(x1, y1, xx1, yy1, xx2, yy2), SquaredDistanceToSegment(x2, y2, xx1, yy1, xx2, yy2)),
        //        Math.Min(SquaredDistanceToSegment(xx1, yy1, x1, y1, x2, y2), SquaredDistanceToSegment(xx2, yy2, x1, y1, x2, y2)));
        //}

        //static int SquaredDistanceToSegment(int x, int y, int x1, int y1, int x2, int y2) {
        //    int result = Math.Min(SquaredDistance(x, y, x1, y1), SquaredDistance(x, y, x2, y2));
        //    if (x1 == x2 && y1 <= y && y <= y2)
        //        result = (x - x1) * (x - x1);
        //    else if (y1 == y2 && x1 <= x && x <= x2)
        //        result = (y - y1) * (y - y1);
        //    return result;
        //}

        static long SquaredDistance(long ax, long ay, long bx, long by) {
            return (ax - bx) * (ax - bx) + (ay - by) * (ay - by);
        }
        #endregion

        #region read helpers
        static int nextInt() {
            int t = input.Read();
            while (t < '0' || t > '9') t = input.Read();
            int x = 0;
            while (t >= '0' && t <= '9') {
                x *= 10;
                x += t - '0';
                t = input.Read();
            }
            return x;
        }

        static long nextLong() {
            int t = input.Read();
            while (t < '0' || t > '9') t = input.Read();
            long x = 0;
            while (t >= '0' && t <= '9') {
                x *= 10;
                x += t - '0';
                t = input.Read();
            }
            return x;
        }

        public static List<int> ReadIntList() {
            return input.ReadLine().Split(' ').Select(x => int.Parse(x)).ToList();
        }

        public static int[] ReadIntArray() {
            return input.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
        }

        public static long[] ReadLongArray() {
            return input.ReadLine().Split(' ').Select(x => long.Parse(x)).ToArray();
        }

        public static List<long> ReadLongList() {
            return input.ReadLine().Split(' ').Select(x => long.Parse(x)).ToList();
        }

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

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

        public static long ReadLong() {
            return long.Parse(input.ReadLine());
        }
#endregion
    }

    public class SegmentTree {
        private int[] a, t;
        private int n;
        public SegmentTree(int[] a) {
            n = a.Length;
            this.a = a;
            t = new int[n << 2];
            buildSegmentTree(0, n - 1, 1);
        }

        private void buildSegmentTree(int l, int r, int v) {
            if (l == r)
                t[v] = a[l];
            else {
                int m = (l + r) >> 1;
                int vl = v << 1;
                int vr = (v << 1) | 1;
                buildSegmentTree(l, m, vl);
                buildSegmentTree(m + 1, r, vr);
                t[v] = t[vl] + t[vr];
            }
        }

        public int QuerySegmentTree(int l, int r) {
            return querySegmentTree(1, l, r, 0, n - 1);
        }

        public void Update(int v, int tl, int tr, int pos, int new_val) {
            if (tl == tr)
                t[v] = new_val;
            else {
                int tm = (tl + tr) / 2;
                if (pos <= tm)
                    Update(v << 1, tl, tm, pos, new_val);
                else
                    Update(v << 1 + 1, tm + 1, tr, pos, new_val);
                t[v] = t[v << 1] + t[v << 1 + 1];
            }
        }

        private int querySegmentTree(int v, int l, int r, int tl, int tr) {
            if (l > r)
                return 0;
            if (l == tl && r == tr)
                return t[v];
            int m = (tl + tr) >> 1;
            return querySegmentTree(v << 1, l, Math.Min(r, m), tl, m) + querySegmentTree((v << 1) | 1, Math.Max(l, m + 1), r, m + 1, tr);
        }
    }
    class Graph : List<List<int>> {
        public Graph(int num): base(num) {
            for (int i = 0; i < num; i++) {
                this.Add(new List<int>());
            }
        }
    }

    class Heap<T> : IEnumerable<T> where T : IComparable<T> {
        private List<T> heap = new List<T>();
        private int heapSize;
        private int Parent(int index) {
            return (index - 1) >> 1;
        }
        public int Count {
            get { return heap.Count; }
        }
        private int Left(int index) {
            return (index << 1) | 1;
        }
        private int Right(int index) {
            return (index << 1) + 2;
        }
        private void Max_Heapify(int i) {
            int l = Left(i);
            int r = Right(i);
            int largest = i;
            if (l < heapSize && heap[l].CompareTo(heap[i]) > 0)
                largest = l;
            if (r < heapSize && heap[r].CompareTo(heap[largest]) > 0)
                largest = r;
            if (largest != i) {
                T temp = heap[largest];
                heap[largest] = heap[i];
                heap[i] = temp;
                Max_Heapify(largest);
            }
        }
        private void BuildMaxHeap() {
            for (int i = heap.Count >> 1; i >= 0; --i)
                Max_Heapify(i);
        }

        public IEnumerator<T> GetEnumerator() {
            return heap.GetEnumerator();
        }

        public void Sort() {
            for (int i = heap.Count - 1; i > 0; --i) {
                T temp = heap[i];
                heap[i] = heap[0];
                heap[0] = temp;
                --heapSize;
                Max_Heapify(0);
            }
        }

        public T Heap_Extract_Max() {
            T max = heap[0];
            heap[0] = heap[--heapSize];
            Max_Heapify(0);
            return max;
        }

        public void Clear() {
            heap.Clear();
            heapSize = 0;
        }

        public void Insert(T item) {
            if (heapSize < heap.Count)
                heap[heapSize] = item;
            else
                heap.Add(item);
            int i = heapSize;
            while (i > 0 && heap[Parent(i)].CompareTo(heap[i]) < 0) {
                T temp = heap[i];
                heap[i] = heap[Parent(i)];
                heap[Parent(i)] = temp;
                i = Parent(i);
            }
            ++heapSize;
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return ((IEnumerable)heap).GetEnumerator();
        }
    }
    public class Treap<T> where T:IComparable<T> {
        private static Random rand = new Random();
        public static Treap<T> Merge(Treap<T> l, Treap<T> r) {
            if (l == null) return r;
            if (r == null) return l;
            Treap<T> res = null;
            if (l.y > r.y) {
                Treap<T> newR = Merge(l.right, r);
                res = new Treap<T>(l.x, l.y, l.left, newR);
            }
            else {
                Treap<T> newL = Merge(l, r.left);
                res = new Treap<T>(r.x, r.y, newL, r.right);
            }
            return res;
        }

        public bool Contains(T key) {
            if (x.CompareTo(key) > 0)
                return left == null ? false : left.Contains(key);
            else if (x.CompareTo(key) < 0)
                return right == null ? false : right.Contains(key);
            return true;
        }

        public void Split(T x, out Treap<T> l, out Treap<T> r) {
            Treap<T> newTree = null;
            if (this.x.CompareTo(x)<0) {
                if (right == null)
                    r = null;
                else
                    right.Split(x, out newTree, out r);
                l = new Treap<T>(this.x, y, left, newTree);
            }
            else {
                if (left == null)
                    l = null;
                else
                    left.Split(x, out l, out newTree);
                r = new Treap<T>(this.x, y, newTree, right);
            }
        }

        public Treap<T> Add(T x) {
            Treap<T> l, r;
            Split(x, out l, out r);
            Treap<T> m = new Treap<T>(x, rand.Next());
            return Merge(Merge(l, m), r);
        }

        private T x;
        private int y;
        private Treap<T> left, right;
        public Treap(T x, int y, Treap<T> l, Treap<T> r) {
            this.x = x;
            this.y = y;
            left = l;
            right = r;
        }
        public Treap(T x, int y) : this(x, y, null, null) { }
        public Treap(T x) : this(x, rand.Next()) { }
    }
    public static class Extensions {
        public static int Max(this int a, int b) {
            return Math.Max(a, b);
        }

        public static int Min(this int a, int b) {
            return Math.Min(a, b);
        }

        public static void Fill(this int[] array, int val) {
            for (int i = 0; i < array.Length; i++) {
                array[i] = val;
            }
        }

        public static void Fill(this double[] array, double val) {
            for (int i = 0; i < array.Length; i++) {
                array[i] = val;
            }
        }

        public static int ToInt(this string s) {
            return int.Parse(s);
        }

        public static string Fill(this char c, int count) {
            char[] r = new char[count];
            for (int i = 0; i < count; ++i)
                r[i] = c;
            return new string(r);
        }

        public static void Print<T>(this IEnumerable<T> arr) {
            foreach (T t in arr)
                Console.Write("{0} ", t);
        }
    }
}


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

namespace CodeForces
{
    class Program
    {
        static bool can(int a, int b)
        {
            if(b==3)
            {
                return (a==1||a==2||a==4||a==5);
            }
            if (b % 2 == 0)
            {
                int mod = a % 4;
                if (mod > 0) return false;
                int div = a / 4;
                int can = (((b - 1) / 2) * ((b - 1) / 2) + 1) / 2;
                return div <= can;
            }
            else
            {
                if (a % 2 == 1)
                {
                    a--;
                }
                int can4 = (((b - 1) / 2) * ((b - 1) / 2) + 1) / 2;
                int can2 = b / 2 / 2 * 2;
                if (a % 4 == 2)
                {
                    if (can2 > 0)
                    {
                        can2--;
                        a -= 2;
                    }
                    else return false;
                }
                can4 += can2 / 2;
                return a  <= can4*4;
            }
        }
        static void Main(string[] args)
        {
            int x;
            x = int.Parse(Console.ReadLine());
            for (int i = 1; i <= 100; i++)
            {
                if (can(x, i))
                {
                    Console.WriteLine(i.ToString());
                    break;
                }
            }

        }
    }
}


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

namespace ConsoleApplication1.CodeForces
{
    public class LowerBoundSortedSet<T> : SortedSet<T>
    {

        private ComparerDecorator<T> _comparerDecorator;

        private class ComparerDecorator<T> : IComparer<T>
        {

            private IComparer<T> _comparer;

            public T LowerBound { get; private set; }
            public T UpperBound { get; private set; }

            private bool _reset = true;

            public void Reset()
            {
                _reset = true;
            }

            public ComparerDecorator(IComparer<T> comparer)
            {
                _comparer = comparer;
            }

            public int Compare(T x, T y)
            {
                int num = _comparer.Compare(x, y);
                if (_reset)
                {
                    LowerBound = y;
                    UpperBound = y;
                }
                if (num >= 0)
                {
                    LowerBound = y;
                    _reset = false;
                }
                if (num <= 0)
                {
                    UpperBound = y;
                    _reset = false;
                }
                return num;
            }
        }

        public LowerBoundSortedSet()
            : this(Comparer<T>.Default) { }

        public LowerBoundSortedSet(IComparer<T> comparer)
            : base(new ComparerDecorator<T>(comparer))
        {
            _comparerDecorator = (ComparerDecorator<T>)this.Comparer;
        }

        public T FindLowerBound(T key)
        {
            _comparerDecorator.Reset();
            this.Contains<T>(key);
            return _comparerDecorator.LowerBound;
        }

        public T FindUpperBound(T key)
        {
            _comparerDecorator.Reset();
            this.Contains<T>(key);
            return _comparerDecorator.UpperBound;
        }
    }
    public abstract class Heap<T> : IEnumerable<T>
    {
        private const int InitialCapacity = 0;
        private const int GrowFactor = 2;
        private const int MinGrow = 1;

        private int _capacity = InitialCapacity;
        private T[] _heap = new T[InitialCapacity];
        private int _tail = 0;

        public int Count { get { return _tail; } }
        public int Capacity { get { return _capacity; } }

        protected Comparer<T> Comparer { get; private set; }
        protected abstract bool Dominates(T x, T y);

        protected Heap() : this(Comparer<T>.Default)
        {
        }

        protected Heap(Comparer<T> comparer) : this(Enumerable.Empty<T>(), comparer)
        {
        }

        protected Heap(IEnumerable<T> collection)
            : this(collection, Comparer<T>.Default)
        {
        }

        protected Heap(IEnumerable<T> collection, Comparer<T> comparer)
        {
            if (collection == null) throw new ArgumentNullException("collection");
            if (comparer == null) throw new ArgumentNullException("comparer");

            Comparer = comparer;

            foreach (var item in collection)
            {
                if (Count == Capacity)
                    Grow();

                _heap[_tail++] = item;
            }

            for (int i = Parent(_tail - 1); i >= 0; i--)
                BubbleDown(i);
        }

        public void Add(T item)
        {
            if (Count == Capacity)
                Grow();

            _heap[_tail++] = item;
            BubbleUp(_tail - 1);
        }

        private void BubbleUp(int i)
        {
            if (i == 0 || Dominates(_heap[Parent(i)], _heap[i]))
                return; //correct domination (or root)

            Swap(i, Parent(i));
            BubbleUp(Parent(i));
        }

        public T GetMin()
        {
            if (Count == 0) throw new InvalidOperationException("Heap is empty");
            return _heap[0];
        }

        public T ExtractDominating()
        {
            if (Count == 0) throw new InvalidOperationException("Heap is empty");
            T ret = _heap[0];
            _tail--;
            Swap(_tail, 0);
            BubbleDown(0);
            return ret;
        }

        private void BubbleDown(int i)
        {
            int dominatingNode = Dominating(i);
            if (dominatingNode == i) return;
            Swap(i, dominatingNode);
            BubbleDown(dominatingNode);
        }

        private int Dominating(int i)
        {
            int dominatingNode = i;
            dominatingNode = GetDominating(YoungChild(i), dominatingNode);
            dominatingNode = GetDominating(OldChild(i), dominatingNode);

            return dominatingNode;
        }

        private int GetDominating(int newNode, int dominatingNode)
        {
            if (newNode < _tail && !Dominates(_heap[dominatingNode], _heap[newNode]))
                return newNode;
            else
                return dominatingNode;
        }

        private void Swap(int i, int j)
        {
            T tmp = _heap[i];
            _heap[i] = _heap[j];
            _heap[j] = tmp;
        }

        private static int Parent(int i)
        {
            return (i + 1) / 2 - 1;
        }

        private static int YoungChild(int i)
        {
            return (i + 1) * 2 - 1;
        }

        private static int OldChild(int i)
        {
            return YoungChild(i) + 1;
        }

        private void Grow()
        {
            int newCapacity = _capacity * GrowFactor + MinGrow;
            var newHeap = new T[newCapacity];
            Array.Copy(_heap, newHeap, _capacity);
            _heap = newHeap;
            _capacity = newCapacity;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _heap.Take(Count).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class MaxHeap<T> : Heap<T>
    {
        public MaxHeap()
            : this(Comparer<T>.Default)
        {
        }

        public MaxHeap(Comparer<T> comparer)
            : base(comparer)
        {
        }

        public MaxHeap(IEnumerable<T> collection, Comparer<T> comparer)
            : base(collection, comparer)
        {
        }

        public MaxHeap(IEnumerable<T> collection) : base(collection)
        {
        }

        protected override bool Dominates(T x, T y)
        {
            return Comparer.Compare(x, y) >= 0;
        }
    }

    public class MinHeap<T> : Heap<T>
    {
        public MinHeap()
            : this(Comparer<T>.Default)
        {
        }

        public MinHeap(Comparer<T> comparer)
            : base(comparer)
        {
        }

        public MinHeap(IEnumerable<T> collection) : base(collection)
        {
        }

        public MinHeap(IEnumerable<T> collection, Comparer<T> comparer)
            : base(collection, comparer)
        {
        }

        protected override bool Dominates(T x, T y)
        {
            return Comparer.Compare(x, y) <= 0;
        }
    }
    static class _4032123
    {
        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';
            }
        }
        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);

        class Node
        {
            public int Number { get; set; }
            public int Depth { get; set; }

        }
        static long Distance(long x1, long y1, long x2, long y2)
        {
            return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
        }
        static void Main(String[] args)
        {
            //var n = int.Parse(Console.ReadLine().TrimEnd());
            var data = Console.ReadLine().TrimEnd().Split(' ').Select(long.Parse).ToList();
            var x1 = data[0];
            var y1 = data[1];
            var x2 = data[2];
            var y2 = data[3];
            var x3 = data[4];
            var y3 = data[5];
            var d1 = Distance(x1, y1, x2, y2);
            var d2 = Distance(x2, y2, x3, y3);
            if (d1 == d2 && (y1-y2)* (x2 - x3) != (y2 - y3) * (x1 - x2))
            {
                writer.WriteLine("Yes");
            } else
            {
                writer.WriteLine("No");
            }

            writer.Flush();

        }
    }
}


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

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

        private static void Main(string[] args)
        {
            writer.WriteLine(Solve(args) ? "Yes" : "No");
            writer.Flush();
        }

        private static bool Solve(string[] args)
        {
            long ax = Next(), ay = Next(), bx = Next(), by = Next(), cx = Next(), cy = Next();

            if ((ax - bx)*(ax - bx) + (ay - by)*(ay - by) == (cx - bx)*(cx - bx) + (cy - by)*(cy - by))
            {
                return (cx - ax)*(cy - by) != (cy - ay)*(cx - bx);
            }

            return false;
        }

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


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

namespace ProgrammingContest.Codeforces.Round91 {
    class C {
        static List<int> num = new List<int>();
        static void gen(long x, int n) {
            if (x <= n) {
                if(x != 0)
                    num.Add((int)x);
                gen(x * 10 + 4, n);
                gen(x * 10 + 7, n);
            }
        }

        static long fact(long n) { long res = 1; while (n > 1) res *= n--; return res; }

        static int n;
        static List<int> val = new List<int>();
        static int dfs(int pos, long k) {
            if (pos > n) return 0;
            int rest = n - pos,
                res = 0;
            for (int i = 0; i < val.Count; i++) {
                if (val[i] == -1) continue;
                if (k < fact(rest)) {
                    if (num.Contains(val[i]) && num.Contains(pos)) {
                        res = 1;
                    }
                    //Console.WriteLine("dfs: {0} {1}", pos, val[i]);
                    val[i] = -1;
                    return res + dfs(pos + 1, k);
                }
                k -= fact(rest);
            }
            throw new Exception();
        }

        static void Main() {
            var xs = Array.ConvertAll<string, int>(Console.ReadLine().Split(' '), int.Parse);
            n = xs[0];
            int k = xs[1]-1;

            for (int v = k, i = 1; i <= n && v != 0; i++) {
                v /= i;
                if (i == n && v != 0) {
                    Console.WriteLine(-1);
                    return;
                }
            }

            gen(0, n);
            num.Sort();
            for (long v = 1, i = 1; i <= n; i++) {
                v *= i;
                if (k < v) {
                    int res = 0;
                    int m = (int)(n - i);
                    int id = -1;
                    //Console.WriteLine("dfs: {0} {1}", m, res);
                    for (int j = 0; j < num.Count; j++) {
                        if (num[j] > m) {
                            res += j;
                            id = j;
                            break;
                        }
                        if (j == num.Count - 1) {
                            Console.WriteLine(num.Count);
                            return;
                        }
                    }
                    //Console.WriteLine("dfs: {0} {1}", m, res);
                    for (int j = m; j < n; j++) {
                        val.Add(j + 1);
                    }
                    Console.WriteLine(dfs(m+1, k) + res);
                    return;
                }
            }
        }
    }
}


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

namespace Task
{
    class Program
    {
        int getCount(int curNum, int maxNum)
        {
            int res = curNum == 0 ? 0 : 1;
            if (curNum * 10L + 4 <= maxNum)
                res += getCount(curNum * 10 + 4, maxNum);
            if (curNum * 10L + 7 <= maxNum)
                res += getCount(curNum * 10 + 7, maxNum);
            return res;
        }

        void swap(int[] arr, int a, int b)
        {
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }

        void permute(int[] array, int k)
        {
            while (k > 1)
            {
                int curFact = 1;
                int prevFact = 1;
                int pos = 1;
                while (curFact < k)
                {
                    pos++;
                    prevFact = curFact;
                    curFact *= pos;
                }
                int absPos0 = array.Length - pos;
                int shift = (k - 1) / prevFact;
                int absPos1 = absPos0 + shift;
                swap(array, absPos0, absPos1);
                if (pos > 1)
                {
                    Array.Sort(array, absPos0 + 1, pos - 1);
                }

                k -= prevFact * shift;
            }
        }

        bool isLucky(int x)
        {
            while (x > 0)
            {
                if (x % 10 != 4 && x % 10 != 7)
                    return false;
                x /= 10;
            }
            return true;
        }

        void Solve()
        {
            // Place your code here
            int n = io.NextInt();
            int k = io.NextInt();

            long fact = 1;
            int numCount = 1;
            for (int i =  2; i <= n && fact <= k; i++)
            {
                fact *= i;
                numCount++;
            }

            if (fact < k)
            {
                io.Print(-1);
                return;
            }

            int firstCnt = n - numCount;

            int ans = getCount(0, firstCnt);
            int[] lastNumbers = new int[numCount];
            for (int i = 0; i < numCount; i++)
                lastNumbers[i] = n - numCount + 1 + i;

            permute(lastNumbers, k);
            for (int i = 0; i < lastNumbers.Length; i++)
                if (isLucky(firstCnt + i + 1) && isLucky(lastNumbers[i]))
                {
                    ans++;
                }

            io.Print(ans);
        }

        MyIo io = new MyIo();

        static void Main(string[] args)
        {
            var p = new Program();

            p.Solve();
            p.io.Close();
        }
    }

    class MyIo
    {
        char[] separators = new char[] { ' ', '\t' };

#if TEST
        TextReader inputStream = new StreamReader("..\\..\\input.txt");
#else
        TextReader inputStream = System.Console.In;
#endif
        TextWriter outputStream = Console.Out;

        string[] tokens;
        int pointer;

        public string NextLine()
        {
            try
            {
                return inputStream.ReadLine();
            }
            catch (IOException)
            {
                return null;
            }
        }

        public string NextString()
        {
            try
            {
                while (tokens == null || pointer >= tokens.Length)
                {
                    tokens = NextLine().Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    pointer = 0;
                }
                return tokens[pointer++];
            }
            catch (IOException)
            {
                return null;
            }
        }

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

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

        public void Print(string format, params object[] args)
        {
            outputStream.Write(format, args);
        }

        public void PrintLine(string format, params object[] args)
        {
            outputStream.WriteLine(format, args);
        }

        public void Print<T>(T o)
        {
            outputStream.Write(o);
        }

        public void PrintLine<T>(T o)
        {
            outputStream.WriteLine(o);
        }

        public void Close()
        {
            inputStream.Close();
            outputStream.Close();
        }
    }
}


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

namespace _Permutations
{
    class ProgramPermutations
    {
        public static int[] Digits(int num)
        {
            var d = new Stack<int>();
            if (num == 0) d.Push(0);

            while (num > 0)
            {
                d.Push(num % 10);
                num /= 10;
            }

            return d.ToArray();
        }

        public static int DigitsToNum(int[] digits)
        {
            var result = 0;
            var mult = 1;
            for (var i = digits.Length - 1; i >= 0; i--)
            {
                result += digits[i] * mult;
                mult *= 10;
            }

            return result;
        }

        static IEnumerable<int[]> GetPerms(List<int> seq)
        {
            seq.Sort();
            var len = seq.Count();
            var n = len - 1;
            var lst = new List<int[]> {seq.ToArray()};

            while (true)
            {
                var k = -1;
                for (var i = 0; i < n; i++)
                {
                    if (seq[i] < seq[i + 1]) k = i;
                }
                if (k == -1) break;
                var l = -1;
                for (var i = 0; i < len; i++)
                {
                    if (seq[k] < seq[i]) l = i;
                }
                var temp = seq[k];
                seq[k] = seq[l];
                seq[l] = temp;

                var seqNext = new int[len];
                for (var i = 0; i <= k; i++)
                {
                    seqNext[i] = seq[i];
                }
                for (var i = n; i > k; i--)
                {
                    seqNext[k + len - i] = seq[i];
                }
                lst.Add(seqNext);
                seq = new List<int>(seqNext);
                //Console.WriteLine(DigitsToNum(seqNext));
            }

            return lst;
        }

        static bool GreaterThan(IList<int> num1, IList<int> num2, int k)
        {
            for (var i = 0; i < k; i++)
            {
                if (num1[i] < num2[i]) return false;
                if (num1[i] > num2[i]) return true;
            }
            return false;
        }

        static bool LessThan(IList<int> num1, IList<int> num2, int k)
        {
            for (var i=0; i<k; i++)
            {
                if (num1[i] > num2[i]) return false;
                if (num1[i] < num2[i]) return true;
            }
            return false;
        }

        static void Main(string[] args)
        {
            if (args.Count() > 0)
            {
                var r = new Random(1021);

                Console.WriteLine("{0} {1}", args[0], args[1]);
                for (var i=0; i<int.Parse(args[0]); i++)
                {
                    for (var j=0; j<int.Parse(args[1]); j++)
                    {
                        Console.Write(r.Next(0, 10));
                    }
                    Console.WriteLine();
                }

                return;
            }

            var strParams = Console.ReadLine();
            if (string.IsNullOrEmpty(strParams)) return;
            var strnk = strParams.Split();
            var n = int.Parse(strnk[0]);
            var k = int.Parse(strnk[1]);
            var nums = new List<List<int>>();
            for (var i = 0; i < n; i++)
            {
                var strNum = Console.ReadLine();
                if (string.IsNullOrEmpty(strNum)) return;
                var num = strNum.Select(c => c - 48).ToList();
                nums.Add(num);
            }

            // Numbers from 0..k-1 in order
            var seq = new List<int>();
            for (var i=0; i<k; i++)
            {
                seq.Add(i);
            }

            // Permute them
            var permsTemplate = GetPerms(seq);

/*
            foreach (var intse in permsTemplate)
            {
                Console.WriteLine(DigitsToNum(intse));
            }
            return;
*/

            var minDifference = Int32.MaxValue;
            foreach (var perm in permsTemplate)
            {
                // Permute each input number according to the same permutation rule
                //var maxNum = Int32.MinValue;
                //var minNum = Int32.MaxValue;
                var maxNum = new List<int>();
                var minNum = new List<int>();
                for (var i = 0; i < k; i++)
                {
                    maxNum.Add(0);
                    minNum.Add(9);
                }

                foreach (var i in nums)
                {
                    var permDigits = new int[k];
                    for (var j = 0; j < k; j++)
                    {
                        permDigits[j] = i[perm[j]];
                    }
                    if (GreaterThan(permDigits, maxNum, k)) maxNum = new List<int>(permDigits);
                    if (LessThan(permDigits, minNum, k)) minNum = new List<int>(permDigits);
                    //var newNum = DigitsToNum(permDigits);
                    //if (newNum > maxNum) maxNum = newNum;
                    //if (newNum < minNum) minNum = newNum;
                }
                var diff = DigitsToNum(maxNum.ToArray()) - DigitsToNum(minNum.ToArray());
                //Console.WriteLine("{0} - {1} = {2}", DigitsToNum(maxNum.ToArray()), DigitsToNum(minNum.ToArray()), diff);
                if (diff < minDifference) minDifference = diff;
            }
            Console.WriteLine(minDifference);
        }
    }
}


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

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

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

            var nn = new int[n][];
            for (int i = 0; i < nn.Length; i++)
            {
                nn[i] = new int[k];
            }
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < k; j++)
                {
                    nn[i][j] = Next();
                }
            }

            var perm = new int[k];
            for (int i = 0; i < k; i++)
            {
                perm[i] = i;
            }

            int min = int.MaxValue;

            do
            {
                int mi = int.MaxValue;
                int ma = int.MinValue;

                for (int i = 0; i < n; i++)
                {
                    int sum = 0;
                    for (int j = 0; j < k; j++)
                    {
                        sum = sum*10 + nn[i][perm[j]];
                    }
                    mi = Math.Min(mi, sum);
                    ma = Math.Max(ma, sum);
                }

                min = Math.Min(min, ma - mi);
            } while (NextPermutation(perm));

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

        private static bool NextPermutation(int[] nn)
        {
            if (nn.Length <= 1) return false;
            int i = nn.Length - 1;
            int last = nn.Length;

            while (true)
            {
                int i1 = i;
                if (nn[--i] < nn[i1])
                {
                    int i2 = last;
                    while (!(nn[i] < nn[--i2]))
                    {
                        ;
                    }
                    int c = nn[i];
                    nn[i] = nn[i2];
                    nn[i2] = c;

                    Reverse(nn, i1, last);
                    return true;
                }
                if (i == 0)
                {
                    Reverse(nn, 0, last);
                    return false;
                }
            }
        }

        private static void Reverse(int[] nn, int first, int last)
        {
            while ((first != last) && (first != --last))
            {
                int c = nn[first];
                nn[first] = nn[last];
                nn[last] = c;
                first++;
            }
        }

        private static int Next()
        {
            int c;
            do
            {
                c = reader.Read();
            } while (c < '0' || c > '9');
            return c - '0';
        }
    }
}


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

public static class P
{
    public static void Main()
    {
        var nm = Console.ReadLine().Split().Select(int.Parse).ToArray();
        var n = nm[0];
        var m = nm[1];

        ModInt[] fib = new ModInt[Max(n, m) + 1];
        fib[0] = 2;
        fib[1] = 2;
        for (int i = 2; i < fib.Length; i++)
            fib[i] = fib[i - 1] + fib[i - 2];

        Console.WriteLine(fib[n] + fib[m] - 2);
    }
}

struct ModInt
{
    const int MOD = 1000000007;
    const long POSITIVIZER = ((long)MOD) << 31;
    long Data;
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public ModInt(long data) { if ((Data = data % MOD) < 0) Data += MOD; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static implicit operator long(ModInt modInt) => modInt.Data;
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static implicit operator ModInt(long val) => new ModInt(val);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator +(ModInt a, int b) => new ModInt() { Data = (a.Data + b + POSITIVIZER) % MOD };
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator +(ModInt a, long b) => new ModInt(a.Data + b);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator +(ModInt a, ModInt b) { long res = a.Data + b.Data; return new ModInt() { Data = res >= MOD ? res - MOD : res }; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator -(ModInt a, int b) => new ModInt() { Data = (a.Data - b + POSITIVIZER) % MOD };
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator -(ModInt a, long b) => new ModInt(a.Data - b);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator -(ModInt a, ModInt b) { long res = a.Data - b.Data; return new ModInt() { Data = res < 0 ? res + MOD : res }; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator *(ModInt a, int b) => new ModInt(a.Data * b);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator *(ModInt a, long b) => a * new ModInt(b);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator *(ModInt a, ModInt b) => new ModInt() { Data = a.Data * b.Data % MOD };
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator /(ModInt a, ModInt b) => new ModInt() { Data = a.Data * GetInverse(b) % MOD };
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public override string ToString() => Data.ToString();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static long GetInverse(long a)
    {
        long div, p = MOD, x1 = 1, y1 = 0, x2 = 0, y2 = 1;
        while (true)
        {
            if (p == 1) return x2 + MOD; div = a / p; x1 -= x2 * div; y1 -= y2 * div; a %= p;
            if (a == 1) return x1 + MOD; div = p / a; x2 -= x1 * div; y2 -= y1 * div; p %= a;
        }
    }
}


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

public class Program
{
    private int N, M;

    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        M = sc.NextInt();

        /*
         * N*Mグリッド
         * すべてのマスに隣接する同じマスの個数　最大1個
         * ランダム
         *
         * ランダムなパターン個数
         */

        /*
         * 1行目OKなパターン
         * 2行目以降 反転...
         *
         *
         * 1列目
         * 2列目 ...
         *
         */

        ModInt ans = 0;
        // 行
        var dp = new ModInt[100001];
        dp[1] = 2;
        dp[0] = 2;
        for (int i = 2; i <= 100000; i++)
        {
            dp[i] += dp[i - 1] + dp[i - 2];
        }

        ans += dp[M] + dp[N];

        Console.WriteLine(ans - 2);
    }

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

namespace round516
{
  class MainClass
  {
    static long solve(long n, long a, long b, long k, long p)
    {
      long result = -1;
      if (n <= k / n / n)
      { // by sweet tooth
        for (long a_extra = p; a_extra <= a; ++a_extra)
          for (long b_extra = 0; b_extra <= b; ++b_extra)
            if ((k - a - a_extra) % (n + a_extra + b_extra) == 0)
              result = Math.Max(result, a_extra + b_extra);
      }
      else
      {
        for (long round = (k - 2 * a - 1) / (2 * n) + 1; round <= (k - a) / n; ++round)
        {
          long a_extra = (k - a) % round;
          if (a_extra < p) a_extra += round;
          long b_extra = (k - a - a_extra) / round - n - a_extra;
          if (b_extra > n - a)
          {
            long t = (b_extra - n + a - 1) / (round + 1) + 1;
            a_extra += round * t;
            b_extra -= (round + 1) * t;
          }
          if (a_extra <= a && b_extra >= 0)
            result = Math.Max(result, a_extra + b_extra);
        }
      }
      return result;
    }

    public static void Main(string[] args)
    {
      var line = Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse);
      var n = line[0];
      var l = line[1];
      var r = line[2];
      var k = line[3];

      if (l > r)
        r = n - l + r + 1;
      else
        r = r - l + 1;
      l = 1;
      var b = n - r;

      long result = -1;

      if (k <= n || k <= r * 2)
      {
        if (r <= k && k <= r * 2)
        {
          long a_extra = k - r;
          result = Math.Min(b + a_extra + 1, n);
        }
      }
      else
      {
        result = Math.Max(solve(n, r, b, k, 0), solve(n, r, b, k + 1, 1));
      }

      Console.WriteLine(result);
    }
  }
}