using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
class Solve{
    public Solve(){}
    StringBuilder sb;
    public static int Main(){
        new Solve().Run();
        return 0;
    }
    void Run(){
        sb = new StringBuilder();
        Calc();
        Console.Write(sb.ToString());
    }
    void Calc(){
        string[] str = Console.ReadLine().Split(' ');
        long M = int.Parse(str[0]);
        long B = int.Parse(str[1]);
        long count = 0;
        for(long i=0;i<=B;i++){
            long j = (B-i)*M;
            long S = (j+1)*i*(i+1)/2 + (i+1)*j*(j+1)/2;
            count = Math.Max(count,S);
        }
        sb.Append(count+"\n");
    }
}


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

namespace CodeForces
{
    class R167_Div2_A
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            string[] s = Console.ReadLine().Split();
            int[] a = new int[n];
            int sum = 0;
            for (int i = 0; i < n; i++)
            {
                a[i] = int.Parse(s[i]);
                sum += a[i];
            }

            int cnt = 0;
            for (int i = 1; i <= 5; i++)
                if ((sum + i) % (n + 1) != 1)
                    cnt++;

            Console.WriteLine(cnt);

        }
    }
}


using System;

public class Test
{
    public static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        int i,sum = 0;
        int way = 0;
        var input = Console.ReadLine().Split(' ');

        for (i = 0; i < n; i++) sum += int.Parse(input[i]);
        for (i = 1; i <= 5; i++) {
            if ((sum + i) % (n + 1) == 1) continue;
            else way++;
        }
        Console.WriteLine(way);
    }

}


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

namespace ConsoleApplication6
{

    class Program
    {
        static void Main(string[] args)
        {
            int n;
            int min;
            string str1;
            n = Convert.ToInt32(Console.ReadLine());
            int[] trass = new int[n];
            int[] razn1 = new int[n - 1];
            int[] razn2 = new int[n - 2];
            int[,] razn2d = new int[n - 2, n - 2];
            int[] max = new int[n - 2];
            str1 = Console.ReadLine();
            string[] strin1 = str1.Split(' ');
            for (int i = 0; i < n; i++)
            {
                trass[i] = int.Parse(strin1[i]);
            }
            for (int i = 0; i < n - 1; i++)
            {
                razn1[i] = trass[i + 1] - trass[i];

            }
            for (int i = 0; i < n - 2; i++)
            {
                razn2[i] = trass[i + 2] - trass[i];

            }

            for (int i = 0; i < n - 2; i++) {
                for (int j = 0; j < n - 2; j++) {
                    if (j == i) { razn2d[i, j] = razn2[j]; };
                    if (j > i) { razn2d[i, j] = razn1[j + 1]; }
                    else if(i!=j) { razn2d[i, j] = razn1[j]; }

                }
            }
            for (int i = 0; i < n - 2; i++) { max[i] = 0; }
            for (int i = 0; i < n - 2; i++) {
                for (int j = 0; j < n - 2; j++) {
                    if (razn2d[i, j] > max[i]) { max[i] = razn2d[i, j]; }

                }
            }
            min = max[0];
            for (int i = 0; i < n - 2; i++) {
                if (max[i] <= min) { min = max[i]; }

            }

            Console.WriteLine(min);

            Console.ReadLine();

        }
    }
}


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

namespace ConsoleApplication25
{
    class Program
    {
        static void Main(string[] args)
        {
            var num = int.Parse(Console.ReadLine());
            var init = Console.ReadLine().Split(' ').Select(int.Parse).ToList();

            int max = int.MaxValue;
            for (int i = 1; i < init.Count - 1; i++)
            {
                var init1 = init.ToList();
                init1.RemoveAt(i);
                var localMax = 0;
                for (int j = 1 ; j < init1.Count; j++)
                {
                    localMax = Math.Max(localMax, init1[j] - init1[j - 1]);
                }

                max = Math.Min(max, localMax);
            }

            Console.WriteLine(max);
            Console.ReadLine();
        }

    }
}


using System;
namespace test
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            int n = Int32.Parse(Console.ReadLine());

            int i = Console.ReadLine().IndexOf('0');
            Console.WriteLine(i == -1 ? n: i+1);
        }
    }
}


using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        Console.ReadLine();
        string s = Console.ReadLine();
        Console.WriteLine(
            s.All(c => c == '1') ? s.Length : s.TakeWhile(c => c == '1').Count() + 1
        );
        Console.ReadLine();
    }
}


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

namespace ConsoleApp {

    class Program {

        static void Main(string[] args) {

            string number = Console.ReadLine().Trim();
            int step = -1;
            MinStep(0, 0, number, Fill(new int[number.Length], 1), ref step);

            Console.WriteLine(step);
        }

        public static bool IsSquare(string number) {

            return Math.Pow((int)Math.Sqrt(int.Parse(number)), 2) == int.Parse(number);
        }

        public static int[] Fill(int[] array, int value) {

            for(int i = 0; i < array.Length; i++) {

                array[i] = value;
            }

            return array;
        }

        public static string GetNumber(string number, int[] usage) {

            var result = new StringBuilder();

            for(int i = 0; i < usage.Length; i++) {

                if(usage[i] == 1) {

                    result.Append(number[i]);
                }
            }

            return result.ToString();
        }

        public static void MinStep(int counter, int total, string number, int[] usage, ref int min) {

            string newNum = GetNumber(number, usage);

            if(newNum != string.Empty && newNum[0] != '0' && IsSquare(GetNumber(number, usage))) {

                min = min == -1 ? total : Math.Min(min, total);

                return;
            }

            if(counter == number.Length) {

                return;
            }

            int[] newUsage = usage.ToList().ToArray();
            newUsage[counter] = 0;
            MinStep(counter + 1, total + 1, number, newUsage, ref min);
            MinStep(counter + 1, total, number, usage, ref min);
        }
    }
}


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

namespace CSharpParser
{
    public class Solution : SolutionBase
    {
        protected override void Solve()
        {
            string s;
            Next(out s);
            var ans = s.Length;
            for (var i = 1; i < 1 << s.Length; i++)
            {
                var cur = "";
                for (var j = 0; j < s.Length; j++)
                    if ((i >> j & 1) != 0)
                        cur += s[j];
                if (cur[0] == '0')
                    continue;
                var x = int.Parse(cur);
                var q = (int)Math.Sqrt(x);
                while (q * q < x) ++q;
                while (q * q > x) --q;
                if (q * q == x)
                    ans = Math.Min(ans, s.Length - cur.Length);
            }
            PrintLine(ans == s.Length ? -1 : ans);
        }
    }

	public static class Algorithm
	{
		private static readonly Random Rnd = new Random();

		public static void Swap<T>(ref T a, ref T b)
		{
			var temp = a;
			a = b;
			b = temp;
		}

		public static T Max<T>(params T[] a)
		{
			var ans = a[0];
			var comp = Comparer<T>.Default;
			for (var i = 1; i < a.Length; i++) ans = comp.Compare(ans, a[i]) >= 0 ? ans : a[i];
			return ans;
		}

		public static T Min<T>(params T[] a)
		{
			var ans = a[0];
			var comp = Comparer<T>.Default;
			for (var i = 1; i < a.Length; i++) ans = comp.Compare(ans, a[i]) <= 0 ? ans : a[i];
			return ans;
		}

		public static void RandomShuffle<T>(IList<T> a, int index, int length)
		{
			if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
			var last = index + length;
			if (last > a.Count) throw new ArgumentException();
			for (var i = index + 1; i < last; i++)
			{
				var j = Rnd.Next(index, i + 1);
				var t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}

		public static void RandomShuffle<T>(IList<T> a)
		{
			RandomShuffle(a, 0, a.Count);
		}

		public static bool NextPermutation<T>(IList<T> a, int index, int length, Comparison<T> compare = null)
		{
			compare = compare ?? Comparer<T>.Default.Compare;
			if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
			var last = index + length;
			if (last > a.Count) throw new ArgumentException();
			for (var i = last - 1; i > index; i--)
				if (compare(a[i], a[i - 1]) > 0)
				{
					var j = i + 1;
					for (; j < last; j++) if (compare(a[j], a[i - 1]) <= 0) break;
					var t = a[i - 1];
					a[i - 1] = a[j - 1];
					a[j - 1] = t;
					for (; i < last - 1; i++, last--)
					{
						t = a[i];
						a[i] = a[last - 1];
						a[last - 1] = t;
					}
					return true;
				}
			for (var i = index; i < last - 1; i++, last--)
			{
				var t = a[i];
				a[i] = a[last - 1];
				a[last - 1] = t;
			}
			return false;
		}

		public static bool NextPermutation<T>(IList<T> a, Comparison<T> compare = null)
		{
			return NextPermutation(a, 0, a.Count, compare);
		}

		public static bool PrevPermutation<T>(IList<T> a, int index, int length, Comparison<T> compare = null)
		{
			compare = compare ?? Comparer<T>.Default.Compare;
			if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
			var last = index + length;
			if (last > a.Count) throw new ArgumentException();
			for (var i = last - 1; i > index; i--)
				if (compare(a[i], a[i - 1]) < 0)
				{
					var j = i + 1;
					for (; j < last; j++) if (compare(a[j], a[i - 1]) >= 0) break;
					var t = a[i - 1];
					a[i - 1] = a[j - 1];
					a[j - 1] = t;
					for (; i < last - 1; i++, last--)
					{
						t = a[i];
						a[i] = a[last - 1];
						a[last - 1] = t;
					}
					return true;
				}
			for (var i = index; i < last - 1; i++, last--)
			{
				var t = a[i];
				a[i] = a[last - 1];
				a[last - 1] = t;
			}
			return false;
		}

		public static bool PrevPermutation<T>(IList<T> a, Comparison<T> compare = null)
		{
			return PrevPermutation(a, 0, a.Count, compare);
		}

		public static int LowerBound<T>(IList<T> a, int index, int length, T value, Comparison<T> compare = null)
		{
			compare = compare ?? Comparer<T>.Default.Compare;
			if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
			if (index + length > a.Count) throw new ArgumentException();
			var ans = index;
			var last = index + length;
			var p2 = 1;
			while (p2 <= length) p2 *= 2;
			for (p2 /= 2; p2 > 0; p2 /= 2) if (ans + p2 <= last && compare(a[ans + p2 - 1], value) < 0) ans += p2;
			return ans;
		}

		public static int LowerBound<T>(IList<T> a, T value, Comparison<T> compare = null)
		{
			return LowerBound(a, 0, a.Count, value, compare);
		}

		public static int UpperBound<T>(IList<T> a, int index, int length, T value, Comparison<T> compare = null)
		{
			compare = compare ?? Comparer<T>.Default.Compare;
			if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
			if (index + length > a.Count) throw new ArgumentException();
			var ans = index;
			var last = index + length;
			var p2 = 1;
			while (p2 <= length) p2 *= 2;
			for (p2 /= 2; p2 > 0; p2 /= 2) if (ans + p2 <= last && compare(a[ans + p2 - 1], value) <= 0) ans += p2;
			return ans;
		}

		public static int UpperBound<T>(IList<T> a, T value, Comparison<T> compare = null)
		{
			return UpperBound(a, 0, a.Count, value, compare);
		}

		public static void Fill<T>(this IList<T> array, T value) where T : struct
		{
			for (var i = 0; i < array.Count; i++)
				array[i] = value;
		}

		public static void Fill<T>(this IList<T> array, Func<int, T> func)
		{
			for (var i = 0; i < array.Count; i++)
				array[i] = func(i);
		}
	}

	public class InStream : IDisposable
	{
		protected readonly TextReader InputStream;
		private string[] _tokens;
		private int _pointer;

		private InStream(TextReader inputStream)
		{
			InputStream = inputStream;
		}

		public static InStream FromString(string str)
		{
			return new InStream(new StringReader(str));
		}

		public static InStream FromFile(string str)
		{
			return new InStream(new StreamReader(str));
		}

		public static InStream FromConsole()
		{
			return new InStream(Console.In);
		}

		public string NextLine()
		{
			try
			{
				return InputStream.ReadLine();
			}
			catch (Exception)
			{
				return null;
			}
		}

		private string NextString()
		{
			try
			{
				while (_tokens == null || _pointer >= _tokens.Length)
				{
					_tokens = NextLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
					_pointer = 0;
				}
				return _tokens[_pointer++];
			}
			catch (Exception)
			{
				return null;
			}
		}

		public bool Next<T>(out T ans)
		{
			var str = NextString();
			if (str == null)
			{
				ans = default(T);
				return false;
			}
			ans = (T)Convert.ChangeType(str, typeof(T));
			return true;
		}

		public T[] NextArray<T>(int length)
		{
			var array = new T[length];
			for (var i = 0; i < length; i++)
				if (!Next(out array[i]))
					return null;
			return array;
		}

		public T[,] NextArray<T>(int length, int width)
		{
			var array = new T[length, width];
			for (var i = 0; i < length; i++)
				for (var j = 0; j < width; j++)
					if (!Next(out array[i, j]))
						return null;
			return array;
		}

		public void Dispose()
		{
			InputStream.Close();
		}
	}

	public class OutStream : IDisposable
	{
		protected readonly TextWriter OutputStream;

		private OutStream(TextWriter outputStream)
		{
			OutputStream = outputStream;
		}

		public static OutStream FromString(System.Text.StringBuilder strB)
		{
			return new OutStream(new StringWriter(strB));
		}

		public static OutStream FromFile(string str)
		{
			return new OutStream(new StreamWriter(str));
		}

		public static OutStream FromConsole()
		{
			return new OutStream(Console.Out);
		}

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

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

		public void PrintLine()
		{
			OutputStream.WriteLine();
		}

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

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

		public void PrintArray<T>(IList<T> a, string between = " ", string after = "\n", bool printCount = false)
		{
			if (printCount)
				PrintLine(a.Count);
			for (var i = 0; i < a.Count; i++)
				Print("{0}{1}", a[i], i == a.Count - 1 ? after : between);
		}

		public void Dispose()
		{
			OutputStream.Close();
		}
	}

	public abstract class SolutionBase : IDisposable
	{
		private InStream _in;
		private OutStream _out;

		protected SolutionBase()
		{
			//System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
			_in = InStream.FromConsole();
			_out = OutStream.FromConsole();
		}

		protected string NextLine()
		{
			return _in.NextLine();
		}

		protected bool Next<T>(out T ans)
		{
			return _in.Next(out ans);
		}

		protected T[] NextArray<T>(int length)
		{
			return _in.NextArray<T>(length);
		}

		protected T[,] NextArray<T>(int length, int width)
		{
			return _in.NextArray<T>(length, width);
		}

		protected void PrintArray<T>(IList<T> a, string between = " ", string after = "\n", bool printCount = false)
		{
			_out.PrintArray(a, between, after, printCount);
		}

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

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

		public void PrintLine()
		{
			_out.PrintLine();
		}

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

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

		public void Dispose()
		{
			_in.Dispose();
			_out.Dispose();
		}

		public void Freopen(string path, FileAccess access)
		{
			switch (access)
			{
				case FileAccess.Read:
					_in.Dispose();
					_in = InStream.FromFile(path);
					break;
				case FileAccess.Write:
					_out.Dispose();
					_out = OutStream.FromFile(path);
					break;
			}
		}

		protected abstract void Solve();

		public static void Main()
		{
			using (var p = new Solution()) p.Solve();
		}
	}
}


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

namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int C = input[0];
            int D = input[1];
            int[] nm = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int N = nm[0];
            int M = nm[1];
            int K = int.Parse(Console.ReadLine());
            int[] problems = new int[N * M + N + 1];
            for (int i = 0; i < problems.Length; i++)
            {
                problems[i] = int.MaxValue;
            }
            problems[1] = D;
            problems[N] = C;
            if (N == 1)
                problems[1] = Math.Min(D, C);
            problems[0] = 0;
            for (int i = 2; i < problems.Length; i++)
            {
                if (i - N >= 0)
                {
                    problems[i] = Math.Min(problems[i - N] + C, (problems[i - 1] + D));
                }
                else
                {
                    problems[i] = problems[i - 1] + D;
                }
            }
            int P = N * M - K;
            int min = int.MaxValue;
            if (P < 0)
                Console.Write(0);
            else
            {
                for (int i = P; i < problems.Length; i++)
                {
                    min = Math.Min(min, problems[i]);
                }
                Console.Write(min);
            }
       //     Console.ReadKey();
        }
    }
}


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

namespace LongPath
{
    public class Problem417A
    {
        public static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
            var c = input[0];
            var d = input[1];

            input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
            var n = input[0];
            var m = input[1];

            var k = int.Parse(Console.ReadLine());

            var mainpp = c / n;

            var count = 0;
            var candidates = n * m - k;

            while (candidates > 0)
            {
                if (d * Math.Min(candidates, n) > c)
                {
                    count += c;
                    candidates -= n;
                }
                else
                {
                    count += d * candidates;
                    candidates = 0;
                }
            }

            Console.WriteLine(count);
        }
    }
}


using System;

namespace Codeforces2
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            string[] mas = s.Split(' ');
            int init = 2;
            double sum = 0;
            double minsum = 0;
            double maxsum = 0;
            for (int i = 0; i < int.Parse(mas[1]); i++)
                sum += Math.Pow(init, i);
            minsum = sum + int.Parse(mas[0]) - int.Parse(mas[1]);
            if (int.Parse(mas[1]) == int.Parse(mas[2]))
                maxsum = sum + (int.Parse(mas[0]) - int.Parse(mas[1])) * Math.Pow(init, int.Parse(mas[1])-1);
            else
            {
                for(int i=int.Parse(mas[1]);i<int.Parse(mas[2]);i++)
                    sum += Math.Pow(init, i);
                maxsum = sum + (int.Parse(mas[0]) - int.Parse(mas[2])) * Math.Pow(init, int.Parse(mas[2])-1);
            }
            Console.Write(minsum.ToString() + " " + maxsum.ToString());

        }
    }
}


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

namespace Training
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] test_numbers = Console.ReadLine().Trim().Split(' ');
            int n = Convert.ToInt32(test_numbers[0]);
            int l = Convert.ToInt32(test_numbers[1]);
            int r = Convert.ToInt32(test_numbers[2]);
            int min_sum = 0, max_sum = 0, max = 0;
            int l_num = 1, r_num = 1;
            for (int i = 0; i < n; i++)
            {
                if (l <= 0)
                {
                    min_sum += 1;
                }
                else
                {
                    min_sum += l_num;
                    l_num *= 2;
                }
                if (r <= 0)
                {
                    max_sum += max;
                }
                else
                {
                    max_sum += r_num;
                    max = r_num;
                    r_num *= 2;
                }
                l--;
                r--;
            }
            Console.WriteLine($"{min_sum} {max_sum}");
        }
    }
}


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

namespace contest
{
    class Program
    {
#if DEBUG
        static readonly TextReader input = File.OpenText(@"../../A/A.in");
        static readonly TextWriter output = File.CreateText(@"../../A/A.out");
#else
        static readonly TextReader input = Console.In;
        static readonly TextWriter output = Console.Out;
#endif

        private static void SolveC()
        {
            //long[] s = input.ReadLine().Split(' ').Select(long.Parse).ToArray();
            int n = int.Parse(input.ReadLine());

            int[][] inp = new int[4*n + 1][];
            for (int i = 0; i <= 4*n; ++i)
            {
                inp[i] = input.ReadLine().Split(' ').Select(int.Parse).ToArray();
            }

            const int Max = 50;

            bool found;
            int xr = 0, yr = 0;
            for (int x = 0; x <= Max; ++x)
            {
                for (int x2 = x; x2 <= Max; ++x2)
                {
                    for (int y = 0; y <= Max; ++y)
                    {
                        int y2 = x2 - x + y;
                        //for (int y2 = y; y2 <= Max; ++y2)
                        {
                            found = false;
                            foreach (int[] xy in inp)
                            {

                                if (!((xy[0] == x && (xy[1] <= y2 && xy[1] >= y)) ||
                                    (xy[0] == x2 && (xy[1] <= y2 && xy[1] >= y))||
                                    (xy[1] == y && (xy[0] <= x2 && xy[0] >= x)) ||
                                    (xy[1] == y2 && (xy[0] <= x2 && xy[0] >= x))))
                                {
                                    xr = xy[0];
                                    yr = xy[1];
                                    if (found)
                                    {
                                        found = false;
                                        break;
                                    }

                                    found = true;
                                }
                            }

                            if (found)
                            {
                                output.Write(xr + " " + yr);
                                return;
                            }
                        }
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            //SolveC();
            SolveC();
            output.Flush();
        }
    }
}


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

using static util;
using P = pair<int, int>;

using Binary = System.Func<System.Linq.Expressions.ParameterExpression,
                           System.Linq.Expressions.ParameterExpression,
                           System.Linq.Expressions.BinaryExpression>;
using Unary = System.Func<System.Linq.Expressions.ParameterExpression,
                          System.Linq.Expressions.UnaryExpression>;

class Program {
    static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
    static Scan sc = new Scan();
    const int M = 1000000007;
    const int M2 = 998244353;
    const long LM = 1L << 60;
    const double eps = 1e-11;
    static void Main(string[] args)
    {
        int n = sc.Int;
        var p = new P[n * 4 + 1];
        var xs = new HashSet<int>();
        var ys = new HashSet<int>();
        for (int i = 0; i < n * 4 + 1; i++)
        {
            p[i] = sc.P;
            xs.Add(p[i].v1);
            ys.Add(p[i].v2);
        }
        foreach (var x1 in xs)
        {
            foreach (var x2 in xs)
            {
                if (x1 >= x2) continue;
                foreach (var y1 in ys)
                {
                    foreach (var y2 in ys)
                    {
                        if (y1 >= y2) continue;
                        var lis = new List<P>();
                        for (int i = 0; i < n * 4 + 1; i++)
                        {
                            if ((p[i].v1 == x1 || p[i].v1 == x2) && y1 <= p[i].v2 && p[i].v2 <= y2 ||
                                (p[i].v2 == y1 || p[i].v2 == y2) && x1 <= p[i].v1 && p[i].v1 <= x2) {
                            }
                            else {
                                lis.Add(p[i]);
                            }
                        }
                        if (lis.Count == 1) {
                            DBG(lis[0]);
                            return;
                        }
                    }
                }
            }
        }

        sw.Flush();
    }

    static void DBG(string a) => Console.WriteLine(a);
    static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
    static void DBG(params object[] a) => DBG(string.Join(" ", a));
    static void Prt(string a) => sw.WriteLine(a);
    static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
    static void Prt(params object[] a) => Prt(string.Join(" ", a));
}
class pair<T, U> : IComparable<pair<T, U>> {
    public T v1;
    public U v2;
    public pair() : this(default(T), default(U)) {}
    public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; }
    public int CompareTo(pair<T, U> a) {
        int c = Comparer<T>.Default.Compare(v1, a.v1);
        return c != 0 ? c : Comparer<U>.Default.Compare(v2, a.v2);
    }
    public override string ToString() => v1 + " " + v2;
    public void Deconstruct(out T a, out U b) { a = v1; b = v2; }
    public static bool operator>(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) > 0;
    public static bool operator<(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) < 0;
    public static bool operator>=(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) >= 0;
    public static bool operator<=(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) <= 0;
}
static class util {
    public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
    public static T sq<T>(T a) => Operator<T>.Multiply(a, a);
    public static T Max<T>(params T[] a) => a.Max();
    public static T Min<T>(params T[] a) => a.Min();
    public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
    static readonly int[] dd = { 0, 1, 0, -1 };
    static readonly string dstring = "RDLU";
    public static P[] adjacents(this P p) => adjacents(p.v1, p.v2);
    public static P[] adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w);
    public static pair<P, char>[] adjacents_with_str(int i, int j)
        => Enumerable.Range(0, dd.Length).Select(k => new pair<P, char>(new P(i + dd[k], j + dd[k ^ 1]), dstring[k])).ToArray();
    public static pair<P, char>[] adjacents_with_str(int i, int j, int h, int w)
        => Enumerable.Range(0, dd.Length).Select(k => new pair<P, char>(new P(i + dd[k], j + dd[k ^ 1]), dstring[k])).Where(p => inside(p.v1.v1, p.v1.v2, h, w)).ToArray();
    public static P[] adjacents(int i, int j)
        => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).ToArray();
    public static P[] adjacents(int i, int j, int h, int w)
        => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).Where(p => inside(p.v1, p.v2, h, w)).ToArray();
    public static void Assert(bool cond) { if (!cond) throw new Exception(); }
    public static Dictionary<T, int> compress<T>(this IEnumerable<T> a)
        => a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i);
    public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.Aggregate(Enumerable.Union));
    public static void swap<T>(ref T a, ref T b) where T : struct { var t = a; a = b; b = t; }
    public static void swap<T>(this IList<T> a, int i, int j) where T : struct { var t = a[i]; a[i] = a[j]; a[j] = t; }
    public static T[] copy<T>(this IList<T> a) {
        var ret = new T[a.Count];
        for (int i = 0; i < a.Count; i++) ret[i] = a[i];
        return ret;
    }
}
static class Operator<T> {
    static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x");
    static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y");
    public static readonly Func<T, T, T> Add = Lambda(Expression.Add);
    public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract);
    public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply);
    public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide);
    public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus);
    public static readonly Func<T, T> Negate = Lambda(Expression.Negate);
    public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile();
    public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile();
}

class Scan {
    StreamReader sr;
    public Scan() { sr = new StreamReader(Console.OpenStandardInput()); }
    public Scan(string path) { sr = new StreamReader(path); }
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public string Str => sr.ReadLine().Trim();
    public pair<T, U> Pair<T, U>() {
        T a; U b;
        Multi(out a, out b);
        return new pair<T, U>(a, b);
    }
    public P P => Pair<int, int>();
    public int[] IntArr => StrArr.Select(int.Parse).ToArray();
    public long[] LongArr => StrArr.Select(long.Parse).ToArray();
    public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
    public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
    bool eq<T, U>() => typeof(T).Equals(typeof(U));
    T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
    T cv<T>(string s) => eq<T, int>()    ? ct<T, int>(int.Parse(s))
                       : eq<T, long>()   ? ct<T, long>(long.Parse(s))
                       : eq<T, double>() ? ct<T, double>(double.Parse(s))
                       : eq<T, char>()   ? ct<T, char>(s[0])
                                         : ct<T, string>(s);
    public void Multi<T>(out T a) => a = cv<T>(Str);
    public void Multi<T, U>(out T a, out U b)
    { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); }
    public void Multi<T, U, V>(out T a, out U b, out V c)
    { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); }
    public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
    { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); }
    public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
    { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); }
}


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

namespace Codeforces
{
	class Program
	{
		static void Main(string[] args)
		{
			string input1 = Console.ReadLine();
			//string input2 = Console.ReadLine();

			//string input3 = Console.ReadLine();
			//string input4 = Console.ReadLine();

			//var inputs1 = input1.Split(new[] { ' ', '}', '{' , ',' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
			//var inputs2 = input2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToList();

			long n = long.Parse(input1);
			double temp = Math.Log(n, 2);
			int result = (int)temp + 1;
			Console.WriteLine(result);
		}
	}
}


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

class Program
{

    #region Read Input
    static string[] lines;
    static int lineIndex = 0;

    static string ReadNextLine()
    {
#if DEBUG
        if (lines == null)
            lines = System.IO.File.ReadAllLines("input.txt");
        return lines[lineIndex++];
#else
        return Console.ReadLine();
#endif
    }
    #endregion

    static void Main(string[] args)
    {
        int n = int.Parse(ReadNextLine());

        int mul = 2;
        for(int i = 0; i < 33; i++)
        {
            if (n < mul)
            {
                Console.WriteLine(string.Format("{0:d}", i + 1));
                break;
            }
            mul *= 2;
        }

#if DEBUG
        Console.ReadKey();
#endif
    }

}


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 void Go()
        {
            int N = GetInt();
            List<int> data = GetIntArr(N);

            int[,] dp = new int[N, 2];
            dp[N - 1, 0] = data[N - 1];
            dp[N - 1, 1] = 0;
            for (int i = N-2; i >= 0; i--)
            {
                if (dp[i + 1, 0] < data[i] + dp[i + 1, 1])
                {
                    dp[i, 0] = data[i] + dp[i + 1, 1];
                    dp[i, 1] = dp[i + 1, 0];
                }
                else
                {
                    dp[i, 1] = data[i] + dp[i + 1, 1];
                    dp[i, 0] = dp[i + 1, 0];
                }
            }

            Wl(dp[0, 1] + " " + dp[0, 0]);
        }

        #region Template

        private static StringBuilder output = new StringBuilder();

        public static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            output.Length = 0;
            Thread main = new Thread(new ThreadStart(s_threadStart), 512 * 1024 * 1024);
            timer.Start();
            main.Start();
            main.Join();
            Console.Write(output);
            timer.Stop();
            Console.Error.WriteLine(timer.ElapsedMilliseconds);
        }

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

            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)
        {
            W(o);
            output.Append(Console.Out.NewLine);
        }

        private static void Wl<T>(IEnumerable<T> enumerable)
        {
            W(enumerable);
            output.Append(Console.Out.NewLine);
        }

        private static void W<T>(T o)
        {
            if (o is double)
            {
                Wd((o as double?).Value, "");
            }
            else if (o is float)
            {
                Wd((o as float?).Value, "");
            }
            else
                output.Append(o.ToString());
        }

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

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

        #endregion
    }
}


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

class Pie{
   Dictionary<int,int>winSize;

   int getSum(int[]arr,int start){
      int sum = 0;
      int len = arr.Length;
      for(int i=start;i<len;i++){
         sum += arr[i];
      }
      return sum;
   }

   int getWinSize(int[]arr, int ind){
      int len = arr.Length;
      int retV = 0;
      int retSum = getSum(arr,ind+1);
      if(ind==(len-1)){
         retV = arr[ind];
      }else if(ind==(len-2)){
         retV = Math.Max(arr[len-1],arr[len-2]);
      }else{
      //dynamic programming
         int remW = winSize[ind+1];
	 int s1 = arr[ind]+(retSum-remW);
	 int s2 = remW;
	 retV = Math.Max(s1,s2);
      }
      return retV;
   }

   public int[]getSizes(int[]slices){
      winSize = new Dictionary<int,int>();
      int nSlices = slices.Length;
      int totalSz = getSum(slices,0);
      for(int i=nSlices-1;i>=0;i--){
         int sz = getWinSize(slices,i);
	 winSize[i] = sz;
      }
      int bs = winSize[0];
      int az = totalSz-bs;
      int[]retArr = new int[]{az,bs};
      return retArr;
   }
       static int[]strToIntArr(String s){
          //s = s.Substring(1,s.Length-2);
	  string[] strArr = s.Split(new char[]{' '});
	  int len = strArr.Length;
          int[] retArr = new int[len];
	  for(int i=0;i<len;i++){
	     string sVal = strArr[i];
	     int intVal = int.Parse(sVal);
	     retArr[i] = intVal;
	  }
          return retArr;
       }
   public static void Main(string[]args){
      Pie p = new Pie();
      string nLn = Console.ReadLine();
      string arrLn= Console.ReadLine();
      int[] arr = strToIntArr(arrLn);
      int[]abSz = p.getSizes(arr);
      Console.WriteLine("{0} {1}",abSz[0],abSz[1]);
   }
};


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

class Program
{
    public class Pair : IComparable<Pair>
    {
        public int L;
        public int R;
        public int Index;
        public bool Inverted;
        public Pair Next;

        public void Invert(int h)
        {
            this.Inverted = !this.Inverted;
            int tmp = L;
            L = h - R;
            R = h - tmp;
        }
        public void Sort(int h)
        {
            if (L <= R && L > h - R)
            {
                this.Invert(h);
            }

            if (L > R && L < h - R)
            {
                this.Invert(h);
            }
        }

        public int CompareTo(Pair other)
        {
            return (this.R - this.L) * this.L.CompareTo(other.L);
        }

        public override string ToString()
        {
            return L + " " + R;
        }
    }

    static void Main(string[] args)
    {
        int n = ReadInt();
        int m = ReadInt();
        int x = 0;
        for (int i = 2; ; i++)
        {
            if (i % 2 == 0) n--;
            if (i % 3 == 0) m--;

            if (i % 6 == 0) x++;
            while (m < 0 && x > 0)
            {
                m++;
                x--;
            }
            while (n < 0 && x > 0)
            {
                n++;
                x--;
            }

            if (m <= 0 && n <= 0 && x<=0)
            {
                Console.WriteLine(i);
                return;
            }
        }
        /*
        int h = ReadInt();
        int n = ReadInt();

        Pair[] m  = new Pair[n];
        Pair[] used = new Pair[h + 1];
        for (int i = 0; i < n; i++)
        {
            m[i] = new Pair()
            {
                L = ReadInt(),
                R = ReadInt(),
                Index = i + 1
            };
            m[i].Sort(h);

            if ((m[0].R - m[0].L != m[i].R - m[i].L) ||
                (m[0].R == m[0].L && m[i].L != m[0].L))
            {
                Console.WriteLine(0);
                return;
            }

            if (m[0].R != m[0].L)
            {
                if (used[m[i].L] == null)
                {
                    used[m[i].L] = m[i];
                }
                else
                {
                    m[i].Invert(h);
                    if (used[m[i].L].Next != null)
                    {
                        Console.WriteLine(0);
                        return;
                    }

                    used[m[i].L].Next = m[i];
                }
            }
        }

        int[] ans = new int[n];
        int start = m[0].L;
        if (m[0].L < m[0].R) start = m.Min(x => x.L);
        if (m[0].L > m[0].R) start = m.Max(x => x.L);

        int d = m[0].R - m[0].L;
        int xx = 0;
        while (true)
        {
            Pair c = null;
            if (used[start] != null)
            {
                c = used[start];
                used[start] = used[start].Next;
            }
            else
            {
                int pos = h - start;
                c = used[pos];
                if (c == null)
                {
                    break;
                }
                used[pos] = used[pos].Next;
                c.Invert(h);
            }

            ans[xx++] = (c.Inverted ? -1 : 1) * c.Index;
            start = c.R;
        }

        if (xx != n)
        {
            Console.WriteLine(0);
            return;
        }

        Console.WriteLine(string.Join(" ", ans));*/
    }

    private static List<int>[] ReadGraph(int n, int m)
    {
        List<int>[] g = new List<int>[n + 1];
        for (int i = 0; i <= n; i++) g[i] = new List<int>();
        for (int i = 0; i < m; i++)
        {
            int a = ReadInt();
            int b = ReadInt();
            g[a].Add(b);
            g[b].Add(a);
        }

        return g;
    }

    private static int[,] ReadGraphAsMatrix(int n, int m)
    {
        int[,] matrix = new int[n + 1, n + 1];
        for (int i = 0; i < m; i++)
        {
            int a = ReadInt();
            int b = ReadInt();
            matrix[a, b] = matrix[b, a] = 1;
        }

        return matrix;
    }

    private static void Sort(ref int a, ref int b)
    {
        if (a > b) Swap(ref a, ref b);
    }

    private static void Swap(ref int a, ref int b)
    {
        int tmp = a;
        a = b;
        b = tmp;
    }

    private const int BufferSize = 1 << 16;
    private static readonly StreamReader consoleReader = new StreamReader(Console.OpenStandardInput(BufferSize), Encoding.ASCII, false, BufferSize);

    private static int ReadInt()
    {
        int ans = 0;
        int mul = 1;
        do
        {
            ans = consoleReader.Read();
            if (ans == -1)
                return 0;
            if (ans == '-') mul = -1;
        } while (ans < '0' || ans > '9');

        ans -= '0';
        while (true)
        {
            int chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans * mul;
            ans = ans * 10 + chr - '0';
        }
    }

    private static ulong ReadULong()
    {
        ulong ans = 0;
        int chr;
        do
        {
            chr = consoleReader.Read();
            if (chr == -1)
                return 0;
        } while (chr < '0' || chr > '9');

        ans = (uint)(chr - '0');
        while (true)
        {
            chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans;
            ans = ans * 10 + (uint)(chr - '0');
        }
    }

    private static long ReadLong()
    {
        long ans = 0;
        int mul = 1;
        do
        {
            ans = consoleReader.Read();
            if (ans == -1)
                return 0;
            if (ans == '-') mul = -1;
        } while (ans < '0' || ans > '9');

        ans -= '0';
        while (true)
        {
            int chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans * mul;
            ans = ans * 10 + chr - '0';
        }
    }

    private static int[] ReadIntArray(int n)
    {
        int[] ans = new int[n];
        for (int i = 0; i < n; i++)
            ans[i] = ReadInt();
        return ans;
    }

    private static long[] ReadLongArray(int n)
    {
        long[] ans = new long[n];
        for (int i = 0; i < n; i++)
            ans[i] = ReadLong();
        return ans;
    }

    private static char[] ReadString()
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (ans < 'a' || ans > 'z');

        List<char> s = new List<char>();
        do
        {
            s.Add((char)ans);
            ans = consoleReader.Read();
        } while (ans >= 'a' && ans <= 'z');

        return s.ToArray();
    }

    private static char[] ReadString(int n)
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (ans < 'a' || ans > 'z');

        char[] s = new char[n];
        int pos = 0;
        do
        {
            s[pos++] = (char)ans;
            ans = consoleReader.Read();
        } while (ans >= 'a' && ans <= 'z');

        return s;
    }

    private static char ReadLetter()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'))
                return (char)ans;
        }
    }

    private static char ReadDigit()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (ans >= '0' && ans <= '9')
                return (char)ans;
        }
    }

    private static int ReadDigitInt()
    {
        while (true)
        {
            return ReadDigit() - (int)'0';
        }
    }

    private static char ReadAnyChar()
    {
        return (char)consoleReader.Read();
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace vce3
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
#if DEBUG
        static bool _useFileInput = false;
#else
        static bool _useFileInput = false;
#endif

        static void Main(string[] args)
        {
            StreamWriter file = null;
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }

#if DEBUG
			if (!_useFileInput)
			{
				Console.SetIn(getInput());
			}
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var max2 = n * 2;
            var max3 = m * 3;

            var need = Math.Min(max2, max3) / 6;
            for (int i = 0; i < need; i++)
            {
                if (max2 == max3)
                {
                    max2 += 2;
                }
                else if (max2 > max3)
                {
                    max3 += 3;
                    //var n3 = max3 + 3;
                    if (max3 % 6 == 0 && max2 >= max3)
                    {
                        need++;
                    }
                }
                else
                {
                    max2 += 2;
                    if (max2 % 6 == 0 && max3 >= max2)
                    {
                        need++;
                    }
                }
            }

            var res = Math.Max(max2, max3);
            Console.WriteLine(res);

            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


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

namespace sdsdsdsdsdsConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            long[] abc = Console.ReadLine().Split(' ').Select(long.Parse).ToArray();
            long a = abc[0], b = abc[1], c = abc[2];
            List<int> ans = new List<int>();
            for (int i = 1; i <= 81; i++)
            {
                long e = b * Pow(i, a) + c;
                if (sum(Convert.ToString(e)) == i && e > 0 && e < 1000000000)
                    ans.Add((int)e);
            }
            ans.Sort();
            Console.WriteLine(ans.Count);
            if (ans.Count > 0)
                foreach (var x in ans)
                {
                    Console.Write(x + " ");
                }
        }
        public static int sum(string x)
        {
            int s = 0;
            for (int i = 0; i < x.Length; i++)
            {
                s += Convert.ToInt32(x[i])-48;
            }
                return s;
        }
        public static long Pow(long x, long y)
        {
            long a = 1;
            for (int i = 0; i < y; i++)
                a = a*x;
            return a;
        }
    }
}


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

namespace ConsoleApplication20
{
    class Program
    {
        static int S(int x)
        {
            int res = x % 10; ;
            do
            {
                x = x / 10;
                res += x % 10;
            }
            while (x / 10 != 0);
            return res;
        }

        static void Main(string[] args)
        {
            int[] inp = Console.ReadLine().Split(new char[1] { ' ' }).Select(int.Parse).ToArray();
            int a = inp[0];
            int b = inp[1];
            int c = inp[2];

            int n = 0;
            StringBuilder s = new StringBuilder(1);
            for (int i = 1; i <= 81; i++)
            {
                double x = b * Math.Pow(i, a) + c;
                if (S((int)x) == i && x <= 999999999)
                {
                    s.Append(x + " ");
                    n += 1;
                }
            }
            Console.WriteLine(n);
            Console.WriteLine(s);
        }
    }
}


/*
 * Сделано в SharpDevelop.
 * Пользователь: alexey
 * Дата: 16.11.2012
 * Время: 19:15
 *
 * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
 */
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using System.IO;
using System;

namespace round_159
{
	class Program
	{
		public static int ReadInt(){

				return int.Parse(Console.ReadLine());

			}

		public static string[] ReadStrArr(){

				return Console.ReadLine().Split(' ');

			}

	    public static int ToInt(Object a){

			return int.Parse(a.ToString());

			}

		public static void print(int[] mas){

		for (int i =0;i<mas.Length;i++)
			Console.Write(mas[i].ToString()+" ");

		}

		public static int[] ReadIntArray(int n,string[] s){
			int[] a = new int[n];
			for(int i =0;i<n;i++){
				a[i]= ToInt(s[i]);
			}
		return a;
		}
		/*

		 */

	public static void Main(string[] args)
		{

		int n = ReadInt();
		int ans =n;

		int dev = n/2;

		while(dev!=0){

			while(n%dev!=0){
				dev--;
			}

			ans+= dev;

			n=dev;

			dev=dev/2;

		}
		Console.WriteLine(ans);
	 //Console.ReadKey();

	}

	}

}


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

namespace taskB
{
    class Program
    {
        static long result = 0;
        static long max = 0;
        static void Count(int a, long result)
        {
            if (a == 1)
            {
                max = Math.Max(result, max);
            }
            else
            {
                bool find = false;
                for (int i = 2; i * i <= a; i++)
                {
                    if (a % i == 0)
                    {
                        Count(a / i, result + a / i);
                        find = true;
                        break;
                    }
                }
                if (!find)
                {
                    Count(1, result + 1);
                }
            }
        }

        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            result = n;
            max = n;
            Count(n, n);
            Console.WriteLine(max);
        }
    }
}


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

namespace TheMonster
{
    class Program
    {
        static void Main(string[] args)
        {
            //Dados
            string txt = Console.ReadLine();
            int a = int.Parse(txt.Split()[0]), b = int.Parse(txt.Split()[1]);

            txt = Console.ReadLine();
            int c = int.Parse(txt.Split()[0]), d = int.Parse(txt.Split()[1]);

            bool achou = false;
            int resultado = 0;

            for (int i = 0; i < 1000; i++)
            {
                for (int j = 0; j < 1000; j++)
                {
                    if (b + a * i == d + c * j)
                    {
                        resultado = b + a * i;

                        achou = true;
                        break;
                    }
                }
                if (achou)
                    break;
            }
            if (achou)
                Console.Write(resultado);
            else
                Console.Write(-1);

        }
    }
}


using System;

namespace C_
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] strArr;
            string str=Console.ReadLine();
            strArr=str.Split(' ');
            int a=Convert.ToInt32(strArr[0]);
            int b=Convert.ToInt32(strArr[1]);
            str=Console.ReadLine();
            strArr=str.Split(' ');
            int c=Convert.ToInt32(strArr[0]);
            int d=Convert.ToInt32(strArr[1]);
            for(int i=0;i<100;i++){
                for(int j=0;j<100;j++){
                    if((a*i)+b==(c*j)+d){
                    Console.WriteLine((a*i)+b);
                    return ;
                    }
                }
            }
            Console.WriteLine(-1);
        }
    }
}


using System;
using System.Text;

namespace vvv
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split(' ');

            int n = int.Parse(s[0]),
                m = int.Parse(s[1]),
                result = 0;

            while (m > 0)
            {
                for (int i = 1; i <= n; i++)
                {
                    m -= i;

                    if (m == 0)
                    {
                        break;
                    }
                    else if (m < 0)
                    {
                        result = m+i;
                        break;
                    }
                }
            }

            Console.WriteLine(result);
        }
    }
}


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

namespace CodeForceContest
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ');
            var n = int.Parse(input[0]);
            var m = int.Parse(input[1]);
            var left = m%(n*(n + 1)/2);
            int count = 0;
            for (; ; )
            {
                if (count <= left) left -= count++;
                else break;
            }
            Console.WriteLine(left);
        }
    }
}


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

class Prog
{
    public static void Main(String[] args)
    {
        int m1 = 0, m2;
        string s1, s2 = "";
        s1 = Console.ReadLine();
        switch (s1)
        {
            case "January"  : m1 = 1; break;
            case "February" : m1 = 2; break;
            case "March"    : m1 = 3; break;
            case "April"    : m1 = 4; break;
            case "May"      : m1 = 5; break;
            case "June"     : m1 = 6; break;
            case "July"     : m1 = 7; break;
            case "August"   : m1 = 8; break;
            case "September": m1 = 9; break;
            case "October"  : m1 = 10; break;
            case "November" : m1 = 11; break;
            case "December" : m1 = 12; break;
        }
        int i = Convert.ToInt32(Console.ReadLine());
        m2 = m1 + i;
        while (m2 > 12) { m2 -= 12; }
        switch (m2)
        {
            case 1: s2 = "January"; break;
            case 2: s2 = "February"; break;
            case 3: s2 = "March"; break;
            case 4: s2 = "April"; break;
            case 5: s2 = "May"; break;
            case 6: s2 = "June"; break;
            case 7: s2 = "July"; break;
            case 8: s2 = "August"; break;
            case 9: s2 = "September"; break;
            case 10: s2 = "October"; break;
            case 11: s2 = "November"; break;
            case 12: s2 = "December"; break;
        }
        Console.WriteLine(s2);
    }
}


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

namespace A.Codecraft_III
{
    class Program
    {
        static void Main(string[] args)
        {
            string actualMonth = Console.ReadLine();
            int numberMonths = int.Parse(Console.ReadLine());
            List<string> months = new List<string> { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
            int actual = (months.IndexOf(actualMonth) + numberMonths) % 12;
            Console.WriteLine(months[actual]);
            Console.ReadLine();
        }
    }
}


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

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

class Sol{
	public void Solve(){

		var d = S.Split(':').Select(s => int.Parse(s)).ToArray();
		int H = d[0], M = d[1];
		for(int i=0;i<720;i++){
			var ss = String.Format("{0:D02}:{1:D02}",H,M);
			if(isPari(ss)){
				Console.WriteLine(i);
				return;
			}
			M++;
			if(M == 60){
				M = 0;
				H++;
				if(H == 24) H = 0;
			}
		}
	}

	bool isPari(String s){
		int N = S.Length;
		int l = N / 2;
		int r = N / 2;
		if(N%2 == 0) l--;
		for(;l>=0;l--){
			if(s[l] != s[r]) return false;
			r++;
		}
		return true;
	}

	String S;
	public Sol(){
		S = rs();
	}

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


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
{
    class _4032
    {
        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 : IComparable
        {
            public long X { get; set; }
            public long Y { get; set; }
            public int CompareTo(object obj)
            {
                if (this.Y > ((Node)obj).Y)
                {
                    return 1;
                }
                if (this.Y == ((Node)obj).Y)
                {
                    return 0;
                }
                return -1;
            }
        }

        static bool isBig(long n, long s)
        {
            long sum = 0;
            var st = n.ToString();
            for (var i=0;i< st.Length; i++)
            {
                sum += long.Parse(st[i].ToString());
            }
            return n - sum >= s;
        }
        static void Main(String[] args)
        {
            var data = Console.ReadLine().Split(':').ToList();
            var first = data[0];
            var second = data[1];
            int i = 0;
            while(first[1] != second[0] || first[0] != second[1])
            {
                if(second == "59")
                {
                    second = "00";
                    var sb = new StringBuilder();
                    var newFirst = int.Parse(first) + 1;
                    if(newFirst == 24)
                    {
                        newFirst = 0;
                    }
                    if (newFirst < 10)
                    {
                        sb.Append("0");
                    }
                    sb.Append(newFirst);
                    first = sb.ToString();
                } else
                {
                    var newSecond = int.Parse(second) + 1;
                    var sb = new StringBuilder();
                    if(newSecond < 10)
                    {
                        sb.Append("0");
                    }
                    sb.Append(newSecond);
                    second = sb.ToString();
                }
                i++;
            }

            Console.WriteLine(i);

        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using SB = System.Text.StringBuilder;
//using System.Threading.Tasks;
//using System.Text.RegularExpressions;
//using System.Globalization;
//using System.Diagnostics;
using static System.Console;
using System.Numerics;
using static System.Math;
using pair = Pair<int, int>;

class Program
{
    static void Main()
    {
        //SetOut(new StreamWriter(OpenStandardOutput()) { AutoFlush = false });
        new Program().solve();
        Out.Flush();
    }
    readonly Scanner cin = new Scanner();
    readonly int[] dd = { 0, 1, 0, -1, 0 }; //→↓←↑
    readonly int mod = 1000000007;
    readonly int dom = 998244353;
    bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (b.CompareTo(a) < 0) { a = b; return true; } return false; }

    bool calc(int day, int[] K, List<int>[] L, int Sum)
    {
        int used = 0;
        int money = day;
        for (int i = day - 1; i >= 0; i--)
        {
            if (i < L.Length)
            {
                foreach (var v in L[i])
                {
                    int buy = Min(K[v], money);
                    money -= buy;
                    K[v] -= buy;
                    used += buy;
                }
            }
            money = Min(i, money);
        }

        int remain = Sum - used;

        return remain * 2 <= (day - used);

    }
    void solve()
    {
        int N = cin.nextint;
        int M = cin.nextint;
        var K = cin.scanint;

        var L = new List<int>[200000];
        for (int i = 0; i < L.Length; i++)
        {
            L[i] = new List<int>();
        }
        for (int i = 0; i < M; i++)
        {
            L[cin.nextint - 1].Add(cin.nextint - 1);
        }
        int Sum = K.Sum();

        int ng = 0;
        int ok = Sum * 2;
        while (ok - ng > 1)
        {
            int mid = (ok + ng) / 2;

            var Z = new int[N];
            for (int i = 0; i < Z.Length; i++)
            {
                Z[i] = K[i];
            }

            if (calc(mid, Z, L, Sum))
            {
                ok = mid;
            }
            else
            {
                ng = mid;
            }
        }

        WriteLine(ok);

    }

}

static class Ex
{
    public static void join<T>(this IEnumerable<T> values, string sep = " ") => WriteLine(string.Join(sep, values));
    public static string concat<T>(this IEnumerable<T> values) => string.Concat(values);
    public static string reverse(this string s) { var t = s.ToCharArray(); Array.Reverse(t); return t.concat(); }

    public static int lower_bound<T>(this IList<T> arr, T val) where T : IComparable<T>
    {
        int low = 0, high = arr.Count;
        int mid;
        while (low < high)
        {
            mid = ((high - low) >> 1) + low;
            if (arr[mid].CompareTo(val) < 0) low = mid + 1;
            else high = mid;
        }
        return low;
    }
    public static int upper_bound<T>(this IList<T> arr, T val) where T : IComparable<T>
    {
        int low = 0, high = arr.Count;
        int mid;
        while (low < high)
        {
            mid = ((high - low) >> 1) + low;
            if (arr[mid].CompareTo(val) <= 0) low = mid + 1;
            else high = mid;
        }
        return low;
    }
}

class Pair<T, U> : IComparable<Pair<T, U>> where T : IComparable<T> where U : IComparable<U>
{
    public T f; public U s;
    public Pair(T f, U s) { this.f = f; this.s = s; }
    public int CompareTo(Pair<T, U> a) => f.CompareTo(a.f) != 0 ? f.CompareTo(a.f) : s.CompareTo(a.s);
    public override string ToString() => $"{f} {s}";
}

class Scanner
{
    string[] s; int i;
    readonly char[] cs = new char[] { ' ' };
    public Scanner() { s = new string[0]; i = 0; }
    public string[] scan => ReadLine().Split();
    public int[] scanint => Array.ConvertAll(scan, int.Parse);
    public long[] scanlong => Array.ConvertAll(scan, long.Parse);
    public double[] scandouble => Array.ConvertAll(scan, double.Parse);
    public string next
    {
        get
        {
            if (i < s.Length) return s[i++];
            string st = ReadLine();
            while (st == "") st = ReadLine();
            s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
            i = 0;
            return next;
        }
    }
    public int nextint => int.Parse(next);
    public long nextlong => long.Parse(next);
    public double nextdouble => double.Parse(next);
}


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

public class Program
{
    int N, M;
    int[] K;
    int[] D, T;
    int[] index;
    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        M = sc.NextInt();
        K = sc.IntArray();
        D = new int[M];
        T = new int[M];
        for (int i = 0; i < M; i++)
        {
            D[i] = sc.NextInt();
            T[i] = sc.NextInt() - 1;
        }
        index = new int[M];
        for (int i = 0; i < M; i++)
        {
            index[i] = i;
        }

        Array.Sort(index, (l, r) => D[l].CompareTo(D[r]));

        // n種類ある
        // 毎日1獲得
        // 通常2 セール中は1支払えば買える
        // 種類iを丁度k[i]個買う
        // 毎日0個以上注文できる
        // 種類t[j]はd[j]日にセール

        //
        int ng = -1;
        int ok = 400000;
        while (ok - ng > 1)
        {
            int mid = (ok + ng) / 2;
            if (C(mid)) ok = mid;
            else ng = mid;
        }

        Console.WriteLine(ok);
    }

    // day日に達成できるか?
    bool C(int day)
    {
        // 区間内セール
        // 種類ごと一番最後
        // 前から

        int[] s = new int[N];
        for (int i = 0; i < N; i++)
        {
            s[i] = int.MaxValue;
        }

        for (int i = 0; i < M; i++)
        {
            if (D[index[i]] <= day)
            {
                s[T[index[i]]] = D[index[i]];
            }
        }

        var tmp = new int[N];
        for (int i = 0; i < N; i++)
        {
            tmp[i] = i;
        }
        Array.Sort(tmp, (l, r) => s[l].CompareTo(s[r]));
        //if (day == 8)
        //{
        //    Console.WriteLine("-----");
        //    Console.WriteLine(day);
        //    Console.WriteLine(string.Join(" ", s));
        //    Console.WriteLine(string.Join(" ", tmp));
        //}
        int nokori = 0;
        int m = 0;
        int p = 0;
        for (int i = 0; i < N; i++)
        {
            if (s[tmp[i]] == int.MaxValue)
            {
                nokori += K[tmp[i]];
            }
            else
            {
                // 買える分
                // s[i] - m

                int tt = Math.Min(K[tmp[i]], s[tmp[i]] - m);
                p += tt;
                m += tt;
                nokori += K[tmp[i]] - tt;
                //if (day == 8)
                //{
                //    Console.WriteLine($"{tmp[i]} {tt} {m}");
                //}
            }
        }
        //if(day == 8)
        //{
        //    Console.WriteLine("aaaa" + m);
        //}
        return nokori * 2 <= day - m;
    }

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

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

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

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

        public string Next()
        {
            while (_index >= _line.Length)
            {
                _line = Console.ReadLine().Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

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

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

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


using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            long n = Convert.ToInt64(Console.ReadLine());long k = n / 2;
            if (n % 2 == 0)
            {

                if (k % 2 == 0)
                {
                    Console.WriteLine("0");
                }
                else
                {
                    Console.WriteLine("1");
                }
            }
            else
            {
                if (k % 2 == 0)
                {
                    Console.WriteLine("1");
                }
                else
                {
                    Console.WriteLine("0");
                }
            }
        }
    }
}


using System;

namespace CSharp
{
    class _1102A
    {
        public static void Main()
        {
            long n = long.Parse(Console.ReadLine());
            Console.WriteLine(((n * (n + 1)) / 2) % 2);
        }
    }
}


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

class Program
{
    static void Main(string[] args)
    {
        int size = Convert.ToInt32(Console.ReadLine());
        if (size == 0){Console.WriteLine(1);return;}
        int modulo = 1;
        for (int index = 0; index < size - 1; index++)
        {
            modulo *= 3;
            if (modulo > 1000003)
            {
                modulo %= 1000003;
            }
        }
        Console.WriteLine(modulo);
    }

}


using System;

class P {
  static void Main() {
    var n = int.Parse(Console.ReadLine()) - 1;
    var res = 1;
    while (n --> 0) res = (res * 3) % 1000003;
    Console.Write(res);
  }
}


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

namespace Op
{
    class Program
    {
        public static int Main(string[] args)
        {
            string[] line = Console.ReadLine().Split();
            long a,b,c,t;
            a=long.Parse(line[0]);
            b=long.Parse(line[1]);
            c=long.Parse(line[2]);
            for (long i=0;i<=Math.Min(a,b);i++)
                if (c==a-i+b-i) {Console.WriteLine("{0} {1} {2}", i,b-i,a-i);return 0;}
            Console.WriteLine("Impossible");
            //Console.ReadKey();
            return 0;
        }

    }
    }


using System;
using System.Collections.Generic;

namespace ConsoleApplication234
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] ok = new string[3]; int a, b, c;
            string read = Console.ReadLine();
            ok = read.Split(' ');
            a = int.Parse(ok[0]);
            b = int.Parse(ok[1]);
            c = int.Parse(ok[2]);

            int s = a + b + c;
            if (s%2==1)
            {
                Console.WriteLine("Impossible");
                return;
            }
            s /= 2;
            a = s - a; b = s - b; c = s - c;
            if (a < 0 || b < 0 || c < 0) Console.WriteLine("Impossible");
            else Console.WriteLine(c + " " + a + " " + b);
            //Console.ReadKey();
        }
    }
}


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

namespace test
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			var n = Int32.Parse (Console.ReadLine ());

			var tList = Console.ReadLine ().Split (' ').Select (x => Int32.Parse (x)).OrderBy(x => x).ToList();

			var T = Int32.Parse (Console.ReadLine ());

			var maxLen = 1;
			var currentLen = 1;

			for (var i = 0; i < n - 1; i++) {
				currentLen = 1;

				for (var j = i + 1; j < n; j++) {
					if (tList [j] - tList [i] > T) {
						break;
					}

					currentLen++;
				}

				if (currentLen > maxLen) {
					maxLen = currentLen;
				}
			}

			Console.WriteLine (maxLen);

		}
	}
}


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

namespace codeforces386
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string[] inx = Console.ReadLine().Split(' ');
            int[] data = new int[n];
            for (int i = 0; i < n; i++)
            {
                data[i] = Convert.ToInt32(inx[i]);
            }
            int t = Convert.ToInt32(Console.ReadLine());
            if (n == 1)
            {
                Console.WriteLine(1);
                return;
            }
            Array.Sort(data);
            int a, b, max, curr;
            a = 0; b = 0;
            max = 0;
            curr = 0;
            while (b < n)
            {
                while (b < n && Math.Abs(data[a] - data[b]) <= t)
                {
                    b++;
                    curr++;
                    if (curr > max) max = curr;
                }
                if (b == n) break;
                while (Math.Abs(data[a] - data[b]) > t)
                {
                    a++;
                    curr--;
                }
            }
            Console.WriteLine(max);
        }
    }
}


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

namespace ConsoleApp15
{
    class Program
    {

        static bool ok(int k, int n, int[] a)
        {
            int cant = 0;
            int m = a.Length;
            for (int i = 0; i < m; i++)
                cant += a[i] / k;
            return cant >= n;
        }

        static void Main(string[] args)
        {
            string[] line = Console.ReadLine().Split(' ');
            int n = int.Parse(line[0]);
            int m = int.Parse(line[1]);
            line = Console.ReadLine().Split(' ');
            int[] a = new int[m];
            for (int i = 0; i < m; i++)
                a[i] = int.Parse(line[i]);
            int[] b = new int[105];
            for (int i = 0; i < m; i++)
                b[a[i]]++;

            int ans = 0;
            int lo = 1;
            int hi = m;
            while(lo <= hi)
            {
                int mid = (lo + hi) >> 1;
                if(ok(mid, n, b))
                {
                    ans = mid;
                    lo = mid + 1;
                }
                else
                {
                    hi = mid - 1;
                }
            }

            Console.WriteLine(ans);

        }
    }
}


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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string no1 = Console.ReadLine();
            List<string> ar1 = no1.Split(' ').ToList();
            List<int> ar = ar1.Select(s => int.Parse(s)).ToList();
            no1 = Console.ReadLine();
            List<string> ar2 = no1.Split(' ').ToList();
            List<int> ar3 = ar2.Select(s => int.Parse(s)).ToList();
            Console.WriteLine(PlainningTheExpedition(ar.ElementAt(0), ar.ElementAt(1), ar3));
          //  Console.ReadKey();

        }
        public static int PlainningTheExpedition(int Participants, int typesOfFood, List<int> foods)
        {
            if (Participants == 0)
            {
                return 0;
            }
            List<int> distinctTypes = foods.Distinct().ToList();
            List<int> noOfPackages = new List<int>();
            distinctTypes.ForEach(x => noOfPackages.Add(foods.Count(y => y == x)));
            noOfPackages.Sort();
            int sum = noOfPackages.Sum();
            int maxdays = sum / Participants;
            if (maxdays == 0){
                return 0;
            }
            for (int i = maxdays; i > 0 ; i--)
            {
                int pos = 0;
                for (int j = 0; j < noOfPackages.Count; j++)
                {
                    pos += noOfPackages[j] / i;
                }
                if (pos >= Participants) {
                    return i;
                }
            }
            return 0;
        }

    }
}
//Planning The expedition
//participants - n , type - h
//list = arrType.distinct;
//forech list (list1.push(arrType.Count(item)))
//index = list1.length-n

//7
// 100 100 9 7 6


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    long Fun(int n, int m, int p, int[] a)
    {
        if (p == n)
        {
            var set = new HashSet<int>();
            for (int mask = 0; mask < 1 << n; mask++)
            {
                int x = 0;
                for (int i = 0; i < n; i++)
                    if ((mask >> i & 1) == 1)
                        x = x * 10 + a[i];
                set.Add(x);
            }
            return set.Count;
        }

        long ret = 0;
        for (int i = 1; i <= m; i++)
        {
            a[p] = i;
            ret += Fun(n, m, p + 1, a);
        }
        return ret;
    }

    const int MOD = 1000000007;

    long Fun2(int n, int m)
    {
        int b = 2 * m - 1;
        long p = m;
        long ret = 2 * m;
        for (int i = 1; i < n; i++)
        {
            ret = (ret * b + p) % MOD;
            p = p * m % MOD;
        }
        return ret;
    }

    public void Solve()
    {
        int n = ReadInt();
        int m = ReadInt();
        Write(Fun2(n, m));
    }

    #region Main

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

    #endregion

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


using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;

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

        //Console.WriteLine(Stupid(1, 1));
        //Console.WriteLine(Stupid(2, 2));
        //Console.WriteLine(Stupid(3, 3));
        //Console.WriteLine(Stupid(4, 6));
        //Console.WriteLine(Stupid(5, 5));
        //Console.WriteLine(Stupid(6, 3));

        //1/mの確率で次の状態に進めるオートマトンが、nターンでi回以上先の状態まで進む通り数

        ModInt comb = Power(m, n);
        ModInt res = comb;
        for (int len = 1; len <= n; len++)
        {
            //len回進めなかった場合
            //つまり、len-1回あたりが出て、n-len+1回はずれ
            comb -= Power(m - 1, n - len + 1) * Factorial(n) / Factorial(len - 1) / Factorial(n - len + 1);
            res += comb * Power(m, len);
        }
        Console.WriteLine(res);
    }

    static List<ModInt> factorialMemo = new List<ModInt>() { 1 };
    static ModInt Factorial(int x)
    {
        for (int i = factorialMemo.Count; i <= x; i++) factorialMemo.Add(factorialMemo.Last() * i);
        return factorialMemo[x];
    }

    static ModInt Power(ModInt n, long m)
    {
        ModInt pow = n;
        ModInt res = 1;
        while (m > 0)
        {
            if ((m & 1) == 1) res *= pow;
            pow *= pow;
            m >>= 1;
        }
        return res;
    }

    static ModInt Stupid(int n, int m)
    {
        List<string> seq = new List<string>() { "" };
        for (int i = 0; i < n; i++)
        {
            var newseq = new List<string>();
            foreach (var item in seq)
            {
                for (int j = 1; j <= m; j++)
                {
                    newseq.Add(item + (char)('0' + j));
                }
            }
            seq = newseq;
        }
        int res = 0;
        Dictionary<string, int> freqs = new Dictionary<string, int>();
        foreach (var item in seq)
        {
            HashSet<string> set = new HashSet<string>() { "" };
            for (int i = 0; i < (1 << item.Length); i++)
            {
                string s = "";
                for (int j = 0; j < item.Length; j++)
                {
                    if ((i >> j & 1) == 1) s += item[j];
                }
                set.Add(s);
            }
            //for (int i = 0; i < item.Length; i++)
            //    for (int j = i + 1; j <= item.Length; j++)
            //        set.Add(item[i..j]);
            foreach (var s in set)
            {
                if (!freqs.ContainsKey(s)) freqs[s] = 0;
                freqs[s]++;
            }
            res += set.Count;
        }
        foreach (var group in freqs.GroupBy(x => x.Value).OrderBy(x => x.Key))
        {
            Console.WriteLine($"{group.Key} {group.Count()} {string.Join(" ", group.Take(30).Select(x => x.Key))}");
        }
        return res;
    }
}

struct ModInt
{
    public const int Mod = 1000000007;
    const long POSITIVIZER = ((long)Mod) << 31;
    long Data;
    public ModInt(long data) { if ((Data = data % Mod) < 0) Data += Mod; }
    public static implicit operator long(ModInt modInt) => modInt.Data;
    public static implicit operator ModInt(long val) => new ModInt(val);
    public static ModInt operator +(ModInt a, int b) => new ModInt() { Data = (a.Data + b + POSITIVIZER) % Mod };
    public static ModInt operator +(ModInt a, long b) => new ModInt(a.Data + b);
    public static ModInt operator +(ModInt a, ModInt b) { long res = a.Data + b.Data; return new ModInt() { Data = res >= Mod ? res - Mod : res }; }
    public static ModInt operator -(ModInt a, int b) => new ModInt() { Data = (a.Data - b + POSITIVIZER) % Mod };
    public static ModInt operator -(ModInt a, long b) => new ModInt(a.Data - b);
    public static ModInt operator -(ModInt a, ModInt b) { long res = a.Data - b.Data; return new ModInt() { Data = res < 0 ? res + Mod : res }; }
    public static ModInt operator *(ModInt a, int b) => new ModInt(a.Data * b);
    public static ModInt operator *(ModInt a, long b) => a * new ModInt(b);
    public static ModInt operator *(ModInt a, ModInt b) => new ModInt() { Data = a.Data * b.Data % Mod };
    public static ModInt operator /(ModInt a, ModInt b) => new ModInt() { Data = a.Data * GetInverse(b) % Mod };
    public static bool operator ==(ModInt a, ModInt b) => a.Data == b.Data;
    public static bool operator !=(ModInt a, ModInt b) => a.Data != b.Data;
    public override string ToString() => Data.ToString();
    public override bool Equals(object obj) => (ModInt)obj == this;
    public override int GetHashCode() => (int)Data;
    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;

namespace equations
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            string[] tmp = new string[2];
            tmp = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(tmp[0]);
            int m = Convert.ToInt32(tmp[1]);

            int max = m;

            if( n >= m)
                max = n;

            int answer = 0;

            for (int a = 0; a <= max; a++)
            {
                for( int b = 0; b <= max; b++)
                {
                    if( (a*a + b == n) && (a + b*b == m))
                        answer ++;

                }

            }

            Console.WriteLine(Convert.ToString(answer));

        }
    }
}


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int count =0;

            String line = Console.ReadLine();
            String[] ps = line.Split(' ');
            int n = int.Parse(ps[0]);
            int m = int.Parse(ps[1]);
            for (int i = 0; i <= 1000; i++)
            {
                for (int j = 0; j <= 1000; j++)
                {
                    if ((i * i) + j == n && i + (j * j) == m)
                        count++;
                }

            }
            Console.WriteLine(count);
        }
    }
}


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

namespace CF
{
    class Program
    {

        static long[] values;

        static void Main(string[] args)
        {

#if DEBUG
            TextReader reader = new StreamReader("../../input.txt");

#else
            TextReader reader = Console.In;
#endif

            //reader.ReadLine();

            values = reader.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();

            if (F()) Console.WriteLine("First");
            else Console.WriteLine("Second");

#if DEBUG
            Console.ReadKey();
#endif

        }

        static bool F()
        {
            if (values[2] * 2 > values[1] || values[2] * 2 > values[0]) return false;
            else return true;
        }
    }
}


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

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

        private static void Solve()
        {
            var input = ReadIntArray();
            var a = input[0];
            var b = input[1];
            var r = input[2];
            if(a >=2*r && b >= 2*r)
            {
                WriteLine("First");
            }
            else
                WriteLine("Second");
        }

        private static int Gcd(int a, int b)
        {
            if (b==0)
                return a;

            return Gcd(b, a%b);
        }

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

            Solve();

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

        #region Reader

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

        private static string[] ReadArray()
        {
            return Console.ReadLine().Split(' ');
        }

        private static List<int> ReadIntArray()
        {
            var input = Console.ReadLine().Split(' ').Select(Int32.Parse).ToList();
            return input;
        }

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

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

        private static int ReadNextInt(string[] input, int index)
        {
            return Int32.Parse(input[index]);
        }

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

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

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

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

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

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

        #endregion
    }
}