import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable long INF = 10L ^^ 18 + 23;

void main()
{
    long b;
    int q, le, m;
    readf("%s %s %s %s", &b, &q, &le, &m);
    readln;

    auto t = readln.chomp.split.map!(to!int).redBlackTree;

    if (abs(b) > le) {
        writeln(0);
        return;
    }

    if (b == 0 || q == 1) {
        if (t.equalRange(b.to!int).empty()) writeln("inf");
        else writeln(0);

        return;
    }

    if (q == 0) {
        if (t.equalRange(0).empty()) writeln("inf");
        else writeln(t.equalRange(b.to!int).empty() ? 1 : 0);

        return;
    }

    if (q == -1) {
        bool isInf = t.equalRange(b.to!int).empty() || t.equalRange((-b).to!int).empty();
        if (isInf) writeln("inf");
        else writeln(0);

        return;
    }

    int ans = 0;
    while (abs(b) <= le) {
        if (t.equalRange(b.to!int).empty()) ++ans;

        b = b * q;
    }

    ans.writeln;
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~"\n", ptrs)==ptrs.length;}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------

void main()
{
	lint b1,q,l,m;
loop:while(read(&b1,&q,&l,&m))
	{
		auto a=arread!int;
		sort(a);
		if(q==1)
		{
			if(bins(a,b1) || abs(b1)>l)writeln(0);
			else writeln("inf");
		}
		else if(q==-1)
		{
			if((bins(a,b1) && bins(a,-1*b1)) || abs(b1)>l)writeln(0);
			else writeln("inf");
		}
		else
		{
			int ans=0;
			while(abs(b1)<=l)
			{
				if(!bins(a,b1))ans++;
				b1*=q;
				if(b1==0)
				{
					if(!bins(a,0))
					{
						writeln("inf");
						goto loop;
					}
					else break;
				}
			}
			writeln(ans);
		}
	}
	//debug system("pause");
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable long INF = 10L ^^ 18 + 23;

void main()
{
    long b;
    int q, le, m;
    readf("%s %s %s %s", &b, &q, &le, &m);
    readln;

    auto t = readln.chomp.split.map!(to!int).redBlackTree;

    if (abs(b) > le) {
        writeln(0);
        return;
    }

    if (b == 0 || q == 1) {
        if (t.equalRange(b.to!int).empty()) writeln("inf");
        else writeln(0);

        return;
    }

    if (q == 0) {
        if (t.equalRange(0).empty()) writeln("inf");
        else writeln(t.equalRange(b.to!int).empty() ? 0 : 1);

        return;
    }

    if (q == -1) {
        bool isInf = t.equalRange(b.to!int).empty() || t.equalRange((-b).to!int).empty();
        if (isInf) writeln("inf");
        else writeln(0);

        return;
    }

    int ans = 0;
    while (abs(b) <= le) {
        if (t.equalRange(b.to!int).empty()) ++ans;

        b = b * q;
    }

    ans.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable long INF = 10L ^^ 18 + 23;

void main()
{
    long b;
    int q, le, m;
    readf("%s %s %s %s", &b, &q, &le, &m);
    readln;

    auto t = readln.chomp.split.map!(to!int).redBlackTree;

    if (b == 0 || q == 1) {
        if (t.equalRange(b.to!int).empty()) writeln("inf");
        else writeln(0);

        return;
    }

    if (q == 0) {
        if (t.equalRange(0).empty()) writeln("inf");
        else writeln(t.equalRange(b.to!int).empty() ? 0 : 1);

        return;
    }

    if (q == -1) {
        bool isInf = t.equalRange(b.to!int).empty() || t.equalRange((-b).to!int).empty();
        if (isInf) writeln("inf");
        else writeln(0);

        return;
    }

    int ans = 0;
    while (abs(b) <= le) {
        if (t.equalRange(b.to!int).empty()) ++ans;

        b = b * q;
    }

    ans.writeln;
}


import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nn = readln.split.to!(int[]);
        auto n0 = nn[0];
        auto n1 = nn[1];
        auto n2 = nn[2];

        char[] rs;
        if (n1 == 0) {
            if (n0 > 0) {
                foreach (_n; 0..n0+1) rs ~= '0';
            } else {
                foreach (_n; 0..n2+1) rs ~= '1';
            }
            writeln(rs);
            continue;
        }

        if (n1%2 == 0) {
            rs ~= '1';
            --n1;
        }
        foreach (_n; 0..n0+1) rs ~= '0';
        foreach (_n; 0..n1/2) rs ~= "10";
        foreach (_n; 0..n2+1) rs ~= '1';

        writeln(rs);
    }
}

// Author: Ivan Kazmenko (gassa@mail.ru)
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

string solve (int [] n)
{
pick_start_loop:
	foreach (v0; [0, 1])
	{
		int [] res;
		auto v = v0;
		res ~= v;
		while (sum (n) > 0)
		{
			if (n[v * 2] > 0)
			{
				n[v * 2] -= 1;
				res ~= v;
			}
			else if (n[1] > 0)
			{
				n[1] -= 1;
				v ^= 1;
				res ~= v;
			}
			else
			{
				continue pick_start_loop;
			}
		}
		return res.map !(text).join;
	}
	assert (false);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.splitter.map !(to !(int)).array;
		writeln (solve (n));
	}
}

import std.stdio;
import std.algorithm;
import std.range;
import std.conv;
import std.string;
import std.array;
import std.meta;
import std.random;

// void check(bool[] res, int n0, int n1, int n2) {
// 	int nn0, nn1, nn2;
// 	assert(res.length > 0);
// 	foreach (i; 0 .. res.length - 1) {
// 		int count;
// 		if (res[i]) count++;
// 		if (res[i + 1]) count++;
// 		if (count ==0) nn0++;
// 		else if (count ==1) nn1++;
// 		else if (count == 2) nn2++;
// 	}
// 	assert(nn0 == n0);
// 	assert(nn1 == n1);
// 	assert(nn2 == n2);
// }

void main() {
	int n = readln.chomp.to!int;
	foreach (t; 0 .. n) {
		int[] ns = readln.chomp.split(" ").map!(to!int).array;
		// int[] ns = new int[3];
		// foreach (i; 0.. 3) {
		// 	ns[i] = uniform!"[]"(2, 1000);
		// }
		int n0 = ns[0], n1 = ns[1], n2 = ns[2];
		bool[] res;
		bool at = true;
		bool dontForget = false;
		if (n1 == 0) {
			if (n2 == 0) {
				res.assumeSafeAppend ~= false;
			}
			else {
				res.assumeSafeAppend ~= true;
			}
		}
		else {
			foreach (i; 0 .. n1 + 1) {
				if (i == n1 && at == true) {
					dontForget = true;
					break;
				}
				res.assumeSafeAppend ~= at;
				at = !at;
			}
		}
		bool[] prepend;
		foreach (i; 0 .. n2) {
			prepend.assumeSafeAppend ~= true;
		}
		res = prepend.assumeSafeAppend ~ res;
		foreach (i; 0 .. n0) {
			res.assumeSafeAppend ~= false;
		}
		if (dontForget) {
			res.assumeSafeAppend ~= true;
		}
		// check(res, n0, n1, n2);
		writeln(res.map!(x => x ? '1' : '0'));
	}
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	foreach (ti; 0..t)
	{
		auto n0 = RD!int;
		auto n1 = RD!int;
		auto n2 = RD!int;

		if (n0 != 0)
			ans[ti] ~= '0';
		foreach (i; 0..n0)
		{
			ans[ti] ~= '0';
		}

		int n1o = n1;
		if (n1 % 2 == 0)
			n1o -= 1;
		if (n0 == 0 && n1 != 0)
			ans[ti] ~= '0';
		foreach (i; 0..n1o)
		{
			if (i % 2 == 0)
				ans[ti] ~= '1';
			else
				ans[ti] ~= '0';
		}

		if (n0 == 0 && n1 == 0)
			ans[ti] ~= '1';
		foreach (i; 0..n2)
		{
			ans[ti] ~= '1';
		}

		if (n1 % 2 == 0 && n1 != 0)
		{
			if (ans[ti][$-1] == '0')
				ans[ti] ~= '1';
			else
				ans[ti] ~= '0';
		}
	}

	foreach (e; ans)
	{
		writeln(e);
	}
	stdout.flush;
	debug readln;
}


import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto x = RD;
		auto y = RD;
		bool[long] set;
		set[x] = true;
		while (x < y)
		{
			if (x % 2 == 0)
				x = x * 3 / 2;
			else
				--x;
			if (set.get(x, false))
				break;
			set[x] = true;
		}
		ans[i] = x >= y;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush();
	debug readln();
}

import std.stdio;
import std.algorithm;

bool go(int x, int y) {
  if(x == 1) {
    return y == 1;
  }
  if(x <= 3) {
    return y <= 3;
  }
  return true;
}

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    int x, y;
    readf(" %s %s", &x, &y);
    writefln(go(x, y) ? "YES" : "NO");
  }
}

import std.stdio;
import std.algorithm;

bool go(int x, int y) {
  if(x == 1) {
    return y == 1;
  }
  if(x == 3) {
    return y <= 3;
  }
  return true;
}

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    int x, y;
    readf(" %s %s", &x, &y);
    writefln(go(x, y) ? "YES" : "NO");
  }
}


import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;

void main()
{
    foreach(_; stdin.byLineCopy())
    {
        writeln("NO");
        stdout.flush();
    }
}

import std.stdio, std.string;
import std.conv, std.math;

int main(string[] args)
{
    string line;
    while ((line = readln.strip) !is null)
    {
        if (line == "Is it rated?") writeln("NO");
        else writeln("YES");
        stdout.flush;
    }
    return 0;
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	foreach (line; stdin.byLineCopy ())
	{
		writeln ("NO");
		stdout.flush ();
	}
}


immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int);
  auto filled = new bool[](n + 1);
  int[] fa;
  foreach(i, ai; a)
    {
      if (ai <= n)
	{
	  if (!filled[ai])
	    {
	      filled[ai] = true;
	      continue;
	    }
	}
      fa ~= ai;
    }
  sort(fa);
  debug writeln(fa);
  int ops = 0;
  foreach_reverse(i; 1 .. n + 1)
    {
      if (!filled[i])
	{
	  debug writeln("trying to fill ", i, " with fa ", fa, " back ", fa.back, " ", i < fa.back/2);
	  if (fa.empty || !(i < (fa.back + (fa.back%2))/2)) return writeln(-1);
	  fa.popBack;
	  ops++;
	  filled[i] = true;
	}
    }
  ops.writeln;
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
// }}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto v = new bool [n + 1];
		foreach (ref c; a)
		{
			if (1 <= c && c <= n && !v[c])
			{
				v[c] = true;
				c = 0;
			}
		}
		a = a.filter !(q{a != 0}).array;
		int res = 0;
		foreach (d; 1..n + 1)
		{
			if (!v[d])
			{
				if (a.front > d * 2)
				{
					res += 1;
					a.popFront ();
				}
				else
				{
					res = -1;
					break;
				}
			}
		}
		writeln (res);
	}
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;

		auto ok = new bool[](n);
		long[] b;
		foreach (i; 0..n)
		{
			if (a[i] <= n)
			{
				if (ok[a[i]-1])
					b ~= a[i];
				else
					ok[a[i]-1] = true;
			}
			else
			{
				b ~= a[i];
			}
		}
		b.sort;

		foreach (i; 0..n)
		{
			if (ok[i]) continue;
			if (b.front <= (i+1)*2)
			{
				ans[ti] = -1;
				break;
			}
			b.popFront;
			++ans[ti];
		}
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		a.sort;

		bool ok = true;
		foreach (i; 0..n)
		{
			if (a[i] == i+1) continue;
			if (a[i] <= (i+1)*2)
			{
				ok = false;
				break;
			}
			++ans[ti];
		}
		if (!ok)
			ans[ti] = -1;
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}


import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

int[][] child;
bool[] visited;

long MOD = 998244353;
long[] fac;

long dfs(uint root) {

    uint nc = 0;

    visited[root] = true;
    long mul = 1;

    foreach (v; child[root]) {
        if (!visited[v]) {
            long ll = dfs(v);
            mul = (mul * ll) % MOD;
            nc++;
        }
    }

    if (root != 0)
        nc++;

    return (fac[nc] * mul) % MOD;
}

void main() {
    GC.disable();

    uint n;

    readf(" %s", n);

    auto a = new long[n];
    auto b = new long[n];
    long tt = 0;
    auto hh = new long[n];
    foreach (i; 0 .. n) {
        long x, y;

        readf(" %s %s", x, y);
        a[i] = x;
        b[i] = y;
        tt -= x;
        tt += y * n;
        if (x < y) {
            hh[i] = 1_00_000_000 + (y - x);
        }
        else
            hh[i] = (y - x);
    }

    sort(hh);
    // writeln(hh);

    foreach (i, e; hh) {
        if (e >= 1_00_000_000)
            tt -= (i + 1) * (e - 1_00_000_000);
        else {
            tt += (i + 1) * (-e);
        }
    }

    writeln(tt);
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!uint;
	auto arr = new long[2][](N);

	foreach (i; 0..N)
	{
		auto a = RD!long;
		auto b = RD!long;
		arr[i] = [a, b];
	}
	auto index = MAKE_IDX!"a[0] - a[1] > b[0] - b[1]"(arr);
	long ans;
	debug writeln(arr);
	foreach (ii, i; index)
	{
		ans += arr[i][0] * ii;
		ans += arr[i][1] * (N - ii - 1);
	}

	writeln(ans);
	stdout.flush();
	debug readln();
}

import std.algorithm.comparison;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.range;
import std.stdio;

void main() {
    int n;
    readf("%s %s", n);
    auto d = new long[](n);
    long s, b;
    foreach (i; 0..n) {
        readf(" %s %s", d[i], b);
        d[i] -= b;
        s += (n-1)*b;
    }
    sort(d);
    foreach (i; 0..n) {
        s += i * d[n-1-i];
    }
    writeln(s);
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(_ => readln.split.map!(to!long).array).array;
    A.sort!"a[0] - a[1] > b[0] - b[1]";
    N.iota.map!(i => A[i][0] * i + A[i][1] * (N - i - 1)).sum.writeln;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T read(T)(){ return read.to!T; }
T[] read(T)(long n){ return n.iota.map!(_ => read!T).array; }
T[][] read(T)(long m, long n){ return m.iota.map!(_ => read!T(n)).array; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

/*
x[j] = a[i](j - 1) + b[i](n - j)
 = (n b[i] - a[i]) + j(a[i] - b[i]).

sum x[j] = sum j[i] c[i], where c[j] = a[i] - b[i].

arrenge so that j[i] is large where c[i] is small.
*/

class X{
	long a;
	long b;
	long c;
	int j;
	long value;
	this(long a, long b){
		this.a = a;
		this.b = b;
		this.c = a - b;
	}
}

void solve(){

	int n = read!int;

	X[] xs;
	foreach(i; 0 .. n){
		long a = read!long;
		long b = read!long;
		xs ~= new X(a, b);
	}
	xs.sort!"a.c>b.c"();
	foreach(i, x; xs) log("i:", i, "a:", x.a, "b:", x.b, "c:", x.c);

	long ans = 0;
	foreach(int i, x; xs){
		x.j = i + 1;
		x.value = x.a * (x.j - 1) + x.b * (n - x.j);
		ans += x.value;
	}
	foreach(i, x; xs) log("i:", i, "a:", x.a, "b:", x.b, "c:", x.c, "j:", x.j, "value:", x.value);

	ans.writeln;

}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!uint;
	auto arr = new int[2][](N);

	foreach (i; 0..N)
	{
		auto a = RD!int;
		auto b = RD!int;
		arr[i] = [a, b];
	}
	auto index = MAKE_IDX!"a[0] - a[1] > b[0] - b[1]"(arr);
	uint ans;
	debug writeln(arr);
	foreach (ii, i; index)
	{
		ans += arr[i][0] * ii;
		ans += arr[i][1] * (N - ii - 1);
	}

	writeln(ans);
	stdout.flush();
	debug readln();
}


import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto x = RD!int;
	auto y = RD!int;
	auto a = RDA;
	int ans;
	foreach (i; 0..n)
	{
		bool ok = true;
		foreach (j; max(0, i-x)..min(n, i+1+y))
		{
			if (a[j] < a[i])
			{
				ok = false;
				break;
			}
		}
		if (ok)
		{
			ans = i+1;
			break;
		}
	}

	writeln(ans);
	stdout.flush();
	debug readln();
}

import std.stdio;
import std.algorithm;

const int MAX = 100005;
int[MAX] a;

void main() {
    int n, x, y;
    readf(" %s %s %s", n, x, y);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) {
        bool ok = true;
        foreach(j; max(0, i-x)..min(i+y+1, n)) {
            ok &= a[j] >= a[i];
        }
        if (ok) {
            writeln(i+1);
            break;
        }
    }
}

import std.stdio;
import std.algorithm : all, map, maxElement, splitter;
import std.array;
import std.string : strip;
import std.conv : to;
import std.range : chain, enumerate, slide, repeat;

void main()
{
  // read array of ints
  int n, x, y;
  readf!"%d %d %d\n"(n, x, y);
  auto a = map!(to!(int))(readln().strip().splitter(' '));
  auto m = a.maxElement;
  auto p = chain(m.repeat(x), a, m.repeat(y)).array;

  foreach (i, win; p.slide(x + y + 1).enumerate(1)) {
    auto mid = win[x];

    if (win.all!(a => a >= mid)) {
      writeln(i);
      break;
    }
  }
}

import std.stdio;
import std.algorithm;

struct obb {
    int index;
    int value;
    int opCmp(obb o) const {
        return value - o.value;
    }
}

const int MAX = 100005;
int[MAX] a;
obb[MAX] o;
bool[MAX] flag;

void main() {
    int n, x, y;
    readf(" %s %s %s", n, x, y);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) o[i] = obb(i, a[i]);
    sort(o[0..n]);

    auto result = o[0].index;
    foreach(i; 0..n) {
        auto index = o[i].index;
        if (flag[index]) continue;
        bool ok = true;
        foreach(j; max(0, index-x)..min(index+y+1, n)) {
            flag[j] = true;
            ok &= a[j] >= o[i].value;
        }
        if (ok) {
            result = min(result, index);
        }
    }
    writeln(result+1);
}


import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;
		if (lo[0] != hi[0])
		{
			res[] = 1;
		}

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;
		if (n == 1)
		{
			writeln (hi[$ - 1]);
			continue;
		}

		uint [] dec (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 0)
				{
					break;
				}
			}
			return res;
		}

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		uint [] calc (uint [] x, uint [] y)
		{
			x = x.dup;
			y = y.dup;
			debug {writeln ("x = ", x);}
			debug {writeln ("y = ", y);}
			auto res = new uint [n];
			while (x[$ - 2..$] != [0, 0])
			{
				res[] ^= x[];
				x = inc (x);
			}
			while (y[$ - 2..$] != [1, 1])
			{
				res[] ^= y[];
				y = dec (y);
			}
			debug {writeln ("z = ", res);}
			return res;
		}

		void getBetter (uint [] x, uint [] y)
		{
			if (x < lo || y > hi)
			{
				return;
			}
			res = max (res, calc (x, y));
		}

		auto pos = 0;
		while (pos < n && lo[pos] == hi[pos])
		{
			pos += 1;
		}
		if (pos < n)
		{
			auto x = lo.dup;
			x[pos + 1..$] = 1;
			auto y = hi.dup;
			y[pos + 1..$] = 0;
			getBetter (x, y);
			if (x.canFind (1))
			{
				getBetter (dec (x), y);
			}
			if (y.canFind (0))
			{
				getBetter (x, inc (y));
			}
		}
		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;
		if (n == 1)
		{
			writeln (1);
			continue;
		}

		uint [] dec (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 0)
				{
					break;
				}
			}
			return res;
		}

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		uint [] calc (uint [] x, uint [] y)
		{
			x = x.dup;
			y = y.dup;
			debug {writeln ("x = ", x);}
			debug {writeln ("y = ", y);}
			auto res = new uint [n];
			while (x[$ - 2..$] != [0, 0])
			{
				res[] ^= x[];
				x = inc (x);
			}
			while (y[$ - 2..$] != [1, 1])
			{
				res[] ^= y[];
				y = dec (y);
			}
			debug {writeln ("z = ", res);}
			return res;
		}

		void getBetter (uint [] x, uint [] y)
		{
			if (x < lo || y > hi)
			{
				return;
			}
			res = max (res, calc (x, y));
		}

		auto pos = 0;
		while (pos < n && lo[pos] == hi[pos])
		{
			pos += 1;
		}
		if (pos < n)
		{
			auto x = lo.dup;
			x[pos + 1..$] = 1;
			auto y = hi.dup;
			y[pos + 1..$] = 0;
			getBetter (x, y);
			if (x.canFind (1))
			{
				getBetter (dec (x), y);
			}
			if (y.canFind (0))
			{
				getBetter (x, inc (y));
			}
		}
		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}


import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto p = RDA!int;

		auto pos = new int[](n);
		foreach (i; 0..n)
			pos[p[i]-1] = i;

		int l = n;
		foreach_reverse (i; 0..n)
		{
			if (pos[i] > l) continue;
			ans[ti] ~= p[pos[i]..l];
			l = pos[i];
		}
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container, std.range;

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

alias X = Tuple!(int, "i", int, "p");

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] PS; get(PS);
        X[] xx;
        foreach (i, p; PS) xx ~= X(i.to!int, p);
        sort!"a.p > b.p"(xx);
        int r = N;
        int[] res;
        foreach (x; xx) if (x.i < r) {
            foreach (i; x.i..r) res ~= PS[i];
            r = x.i;
        }
        writefln!"%(%d %)"(res);
    }
}


// Cheese-Cracker: cheese-cracker.github.io

void theCode(){
    int n;
    n = scan!int;
    ll x = scan;
    auto arr = scanArray;
    ll summ = arr.sum;
    ll[] pows;
    foreach(el; arr){
        ll tim = 0;
        ll num = el;
        while(num > 0 && num % x == 0){
            num /= x;
            ++tim;
        }
        pows ~= tim;
    }
    for(int i = 0; i < 64; ++i){
        for(int j = 0; j < n; ++j){
            if(!pows[j]){
                writeln(summ);
                return;
            }
            summ += arr[j];
            --pows[j];
        }
    }
}

void main(){
    long tests = 1;
    tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container, std.range;

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int N; long X; get(N, X);
        long[] AA; get(AA);
        alias A = Tuple!(long, "c", long, "v");
        auto aa = AA.map!(a => A(1, a)).array();
        int i;
        bool broken;
        long r;
        while (i < aa.length) {
            auto a = aa[i++];
            r += a.v * a.c;
            if (!broken && a.v % X == 0) {
                aa ~= A(a.c * X, a.v / X);
            } else {
                broken = true;
            }
        }
        writeln(r);
    }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD!int;
		auto a = RDA;

		ans[ti] = a.sum;
		(){
		foreach (cnt; 1..10^^5)
		{
			foreach (i; 0..n)
			{
				if (a[i] % x) return;

				auto y = a[i] / x;
				ans[ti] += y * x^^cnt;
				a[i] = y;
			}
		}}();
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}


import std.algorithm;
import std.array;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto s = readln.strip;
		auto v = n.iota.filter !(x => s[x] == '0').array;
		debug {writeln (v);}

		int res = n;
		int p = 0;
		int q = 0;
		int r = k;

		int dist (int t)
		{
			return max (v[t] - v[p], v[r] - v[t]);
		}

		while (r < v.length)
		{
			q = max (q, p);
			while (q < r && dist (q + 1) <= dist (q))
			{
				q++;
			}
			res = min (res, dist (q));
			p++;
			r++;
		}

		writeln (res);
	}
}

import std.stdio;
import std.algorithm;
import std.typecons;
import std.string;
import std.array;
import std.conv;
import std.math;

void main() {
  int n, k;
  readf(" %s %s", &n, &k);
  readln;
  string s = readln.strip;

  auto cnt = new int[n];
  foreach (i; 0..n) {
    cnt[i] = s[i] == '0';
    if (i > 0) cnt[i] += cnt[i - 1];
  }

  bool check(int x) {
    foreach (i; 0..n) {
      int l = max(0, i - x);
      int r = min(n - 1, i + x);
      int q = cnt[r] - (l > 0 ? cnt[l - 1] : 0);
      if (q >= k + 1 && s[i] != '1') {
        return true;
      }
    }
    return false;
  }

  int lo = -1, hi = n * 2;
  while (lo + 1 < hi) {
    int mid = (lo + hi) >> 1;
    if (check(mid)) hi = mid;
    else lo = mid;
  }

  writeln(hi);
}


//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias Task = Tuple!(uint, uint);

void main() {
  auto r = new InputReader;
  immutable nt = r.next!uint;
  auto res = uninitializedArray!(int[]) (nt);
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint;
    immutable T = r.next!uint;
    immutable a = r.next!uint;
    immutable b = r.next!uint;
    auto d = r.nextA!uint (n);
    auto t = r.nextA!uint (n);
    Task[] easy;
    Task[] hard;
    foreach (i; 0 .. n) {
      if (d[i]) {
        hard ~= Task (t[i], 1);
      } else {
        easy ~= Task (t[i], 0);
      }
    }
    sort (easy);
    sort (hard);
    debug stderr.writeln (easy);
    debug stderr.writeln (hard);
    auto m = merge (easy, hard);
    long curt;
    long ce = easy.length, ch = hard.length;
    long best;
    int k;
    while (!m.empty) {
      auto q = m.front;
      debug stderr.writeln (q, ", curt = ", curt);
      auto dt = q[0] - curt;
      if (dt > 0) {
        --dt;
        debug stderr.writefln ("dt = %d", dt);
        long k1 = min (dt / a, ce);
        dt -= k1 * a;
        long k2 = min (dt / b, ch);
        best = max (best, k + k1 + k2);
        debug stderr.writefln ("k = %d, k1 = %d, k2 = %d", k, k1, k2);
      }
      if (q[1]) {
        curt += b;
        --ch;
      } else {
        curt += a;
        --ce;
      }
      m.popFront ();
      ++k;
    }
    if (curt <= T) {
      best = n;
    }
    res[tid] = best.to!int;
  }
  writefln ("%(%s\n%)", res);
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int m = rint;
	foreach(_; 0 .. m){
		int n = rint;
		long tAll = rlong, a = rlong, b = rlong;
		int[] hs = rint(n);
		long[] ts = rlong(n);

		P[] ps;
		foreach(i; 0 .. n) ps ~= P(!!hs[i], ts[i]);
		ps.sort!"a.time < b.time"();

		long xAll, yAll;
		foreach(p; ps) if(p.isHard) yAll += 1; else xAll += 1;

		ps ~= P(0, tAll + 1);
		log("---");
		log("n:", n, "tAll:", tAll, "a:", a, "b:", b);
		log("ps:", ps, "xAll:", xAll, "yAll:", yAll);

		long x = 0, y = 0;
		long best = 0;
		foreach(p; ps){
			log("p:", p, "x:", x, "y:", y);
			if(p.time - 1 >= a * x + b * y){
				long t = (p.time - 1) - (a * x + b * y);
				long s = x + y;
				long x1 = min(xAll - x, t / a);
				if(x1 > 0){
					t -= x1 * a;
					s += x1;
				}
				long y1 = min(yAll - y, t / b);
				if(y1 > 0){
					t -= y1 * b;
					s += y1;
				}
				best.chmax(s);
				log("t:", t, "s:", s, "x1:", x1, "y1:", y1, "best:", best);
			}
			if(p.isHard) y += 1;
			else x += 1;
		}

		best.writeln;
	}
}

struct P{
	bool isHard;
	long time;
}


import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto p = readln.splitter.map !(to !(int)).array;

		auto b = new short [] [] (n, n);
		auto c = new short [] [] (n, n);
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				b[i][j] = (p[i] < p[j]);
				c[i][j] = (p[i] > p[j]);
			}
		}
		foreach (i; 1..n)
		{
			foreach (j; i + 1..n)
			{
				b[i][j] += b[i - 1][j];
			}
		}
		foreach_reverse (i; 0..n)
		{
			foreach_reverse (j; i + 1..n - 1)
			{
				c[i][j] += c[i][j + 1];
			}
		}

		// (<j) j | i (>i)
		long res = 0;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				auto lo = (i > 0) ? b[i - 1][j] : 0;
				auto hi = (j + 1 < n) ? c[i][j + 1] : 0;
				res += lo * hi;
			}
		}
		writeln (res);
	}
}

import std.stdio;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
alias RSQ = SegmentTree!(int, 0, (a, b) => a + b);

struct BIT(Num, Num zero) {
    int N;
    Num[] dat; // dat is 1-indexed
    this(int N) {
        this.N = N;
        dat = new Num[N + 1];
        dat[] = zero;
    }
    // add x to i-th (0-indexed) element
    void add(int i, Num x) {
        i++; // make 1-indexed
        while (i <= N) {
            dat[i] += x;
            i += i & -i;
        }
    }
    // return the sum of [0, i) (0-indexed) element
    Num query(int i) {
        Num s = zero;
        while (i > 0) {
            s += dat[i];
            i -= i & -i;
        }
        return s;
    }
}

void solve() {
    int N = readln.chomp.to!int;
    auto P = readln.chomp.split(" ").map!(to!int).array;

    long ans = 0;
    auto front = BIT!(int,0)(N+1);
    for (int b = 0; b < N; b++) {
        auto back = BIT!(int,0)(N+1);
        for (int c = N-1; c > b; c--) {
            long a_count = front.query(P[c]);
            long d_count = back.query(P[b]);
            ans += a_count * d_count;
            back.add(P[c], 1);
        }
        front.add(P[b], 1);
    }
    writeln(ans);
}

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) solve();
}

import std.stdio;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
alias RSQ = SegmentTree!(int, 0, (a, b) => a + b);

void solve() {
    int N = readln.chomp.to!int;
    auto P = readln.chomp.split(" ").map!(to!int).array;

    alias T = Tuple!(int,int);

    long ans = 0;
    auto front = RSQ(N+1);
    for (int b = 0; b < N; b++) {
        auto back = RSQ(N+1);
        for (int c = N-1; c > b; c--) {
            auto a_count = front.query(1, P[c]);
            long d_count = back.query(1, P[b]);
            ans += a_count * d_count;
            back.update(P[c], 1);
        }
        front.update(P[b], 1);
    }
    writeln(ans);
}

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) solve();
}


import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int limit = 50_000;

void main ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	for (uint g = 2; g * g < limit; g++)
	{
		if (s[g])
		{
			for (uint e = g; e * g < limit; e++)
			{
				s[e * g] = false;
			}
		}
	}

	uint [] p;
	foreach (g; 0..limit)
	{
		if (s[g])
		{
			p ~= g;
		}
	}

	uint n;
	uint a, b, c, d;
	while (readf (" %s %s %s %s %s", &n, &a, &b, &c, &d) > 0)
	{
		uint res = 0;
		auto t = new bool [limit];
		for (uint start = 0; start <= n; start += limit)
		{
			uint finish = min (start + limit, n + 1);
			if (start == 0)
			{
				t[] = s[];
			}
			else
			{
				t[] = true;
				foreach (g; p)
				{
					uint lo = (start + g - 1) / g * g;
					while (lo < finish)
					{
						t[lo - start] = false;
						lo += g;
					}
				}
			}
			foreach (i; start..finish)
			{
				if (t[i - start])
				{
					debug {writeln (i);}
					uint cur = a;
					cur = cur * i + b;
					cur = cur * i + c;
					cur = cur * i + d;

					uint mult = 0;
					uint k = n;
					while (k > 0)
					{
						k /= i;
						mult += k;
					}
					res += cur * mult;
				}
			}
		}
		writeln (res);
	}
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

// floor(sqrt(a))
long floorSqrt(long a) {
  import core.bitop : bsr;
  import std.algorithm : min;
  long b = a, x = 0, y = 0;
  for (int e = bsr(a) & ~1; e >= 0; e -= 2) {
    x <<= 1;
    y <<= 1;
    if (b >= (y | 1) << e) {
      b -= (y | 1) << e;
      x |= 1;
      y += 2;
    }
  }
  return x;
}

// get([N / j]) = \sum_{p<=[N/j]} p^K
//   O(N^(3/4) / log N) time, O(N^(1/2)) space
class PrimeSum(T, int K) {
  long N, sqrtN;
  bool[] isPrime;
  T[] small, large;
  this(long N) {
    assert(N >= 1, "PrimeSum: N >= 1 must hold");
    this.N = N;
    sqrtN = floorSqrt(N);
    isPrime = new bool[cast(int)(sqrtN + 1)];
    small = new T[cast(int)(sqrtN + 1)];
    large = new T[cast(int)(sqrtN + 1)];
    isPrime[2 .. $] = true;
    T powerSum(long n) {
      static if (K == 0) {
        return T(n);
      } else static if (K == 1) {
        long n0 = n, n1 = n + 1;
        ((n0 % 2 == 0) ? n0 : n1) /= 2;
        return T(n0) * T(n1);
      } else static if (K == 2) {
        long n0 = n, n1 = n + 1, n2 = 2 * n + 1;
        ((n0 % 2 == 0) ? n0 : n1) /= 2;
        ((n0 % 3 == 0) ? n0 : (n1 % 3 == 0) ? n1 : n2) /= 3;
        return T(n0) * T(n1) * T(n2);
      } else static if (K == 3) {
        long n0 = n, n1 = n + 1;
        ((n0 % 2 == 0) ? n0 : n1) /= 2;
        return T(n0) * T(n0) * T(n1) * T(n1);
      } else {
        static assert(false, "PrimeSum: K is out of range");
      }
    }
    foreach (n; 1 .. sqrtN + 1) small[cast(int)(n)] = powerSum(n);
    foreach (l; 1 .. sqrtN + 1) large[cast(int)(l)] = powerSum(N / l);
    foreach (p; 2 .. sqrtN + 1) {
      if (isPrime[cast(int)(p)]) {
        for (long n = p^^2; n <= sqrtN; n += p) isPrime[cast(int)(n)] = false;
        const pk = T(p)^^K, g1 = get(p - 1);
        foreach (l; 1 .. sqrtN + 1) {
          const n = N / l;
          if (n < p^^2) break;
          large[cast(int)(l)] -= pk * (get(n / p) - g1);
        }
        foreach_reverse (n; 1 .. sqrtN + 1) {
          if (n < p^^2) break;
          small[cast(int)(n)] -= pk * (get(n / p) - g1);
        }
      }
    }
    small[1 .. $] -= T(1);
    large[1 .. $] -= T(1);
  }
  T get(long n) {
    return (n <= sqrtN) ? small[cast(int)(n)] : large[cast(int)(N / n)];
  }
}

void main() {
  try {
    for (; ; ) {
      const N = readLong();
      const A = readLong();
      const B = readLong();
      const C = readLong();
      const D = readLong();

      auto ps3 = new PrimeSum!(long, 3)(N);
      auto ps2 = new PrimeSum!(long, 2)(N);
      auto ps1 = new PrimeSum!(long, 1)(N);
      auto ps0 = new PrimeSum!(long, 0)(N);
      long get(long n) {
        return A * ps3.get(n) + B * ps2.get(n) + C * ps1.get(n) + D * ps0.get(n);
      }

      long ans;
      for (long a = 0, b; b < N; a = b) {
        const k = N / (a + 1);
        b = N / k;
        // (a, b]: k
        ans += k * (get(b) - get(a));
      }
      foreach (p; 2 .. ps0.sqrtN + 1) {
        if (ps0.isPrime[cast(int)(p)]) {
          const f = get(p) - get(p - 1);
          for (long n = N / p^^2; n >= 1; n /= p) {
            ans += n * f;
          }
        }
      }
      ans &= (1L << 32) - 1;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

// floor(sqrt(a))
long floorSqrt(long a) {
  import core.bitop : bsr;
  import std.algorithm : min;
  long b = a, x = 0, y = 0;
  for (int e = bsr(a) & ~1; e >= 0; e -= 2) {
    x <<= 1;
    y <<= 1;
    if (b >= (y | 1) << e) {
      b -= (y | 1) << e;
      x |= 1;
      y += 2;
    }
  }
  return x;
}

// // pi([N / l]) = get([N / l]) - 1
uint solve(int N, uint A, uint B, uint C, uint D) {
  const sqrtN = cast(int)(floorSqrt(N));
  stderr.writefln("N = %s, sqrtN = %s", N, sqrtN);
  stderr.flush;
  auto small0 = new uint[sqrtN + 1];
  auto large0 = new uint[sqrtN + 1];
  auto small1 = new uint[sqrtN + 1];
  auto large1 = new uint[sqrtN + 1];
  auto small2 = new uint[sqrtN + 1];
  auto large2 = new uint[sqrtN + 1];
  auto small3 = new uint[sqrtN + 1];
  auto large3 = new uint[sqrtN + 1];
  uint get0(int n) { return (n <= sqrtN) ? small0[n] : large0[N / n]; }
  uint get1(int n) { return (n <= sqrtN) ? small1[n] : large1[N / n]; }
  uint get2(int n) { return (n <= sqrtN) ? small2[n] : large2[N / n]; }
  uint get3(int n) { return (n <= sqrtN) ? small3[n] : large3[N / n]; }

  uint calc0(int n) {
    return n;
  }
  uint calc1(int n) {
    uint n0 = n, n1 = n + 1;
    ((n0 % 2 == 0) ? n0 : n1) /= 2;
    return n0 * n1;
  }
  uint calc2(int n) {
    uint n0 = n, n1 = n + 1, n2 = 2 * n + 1;
    ((n0 % 2 == 0) ? n0 : (n1 % 2 == 0) ? n1 : n2) /= 2;
    ((n0 % 3 == 0) ? n0 : (n1 % 3 == 0) ? n1 : n2) /= 3;
    return n0 * n1 * n2;
  }
  uint calc3(int n) {
    uint n0 = n, n1 = n + 1;
    ((n0 % 2 == 0) ? n0 : n1) /= 2;
    return n0 * n0 * n1 * n1;
  }

  foreach (n; 1 .. sqrtN + 1) {
    // small[n] = n;
    small0[n] = calc0(n);
    small1[n] = calc1(n);
    small2[n] = calc2(n);
    small3[n] = calc3(n);
  }
  foreach_reverse (l; 1 .. sqrtN + 1) {
    // large[l] = N / l;
    large0[l] = calc0(N / l);
    large1[l] = calc1(N / l);
    large2[l] = calc2(N / l);
    large3[l] = calc3(N / l);
  }
  auto isnp = new bool[sqrtN + 1];
  int pi;
  foreach (p; 2 .. sqrtN + 1) {
    // if (small[p - 1] < small[p]) {
    if (!isnp[p]) {
      for (int n = 2 * p; n <= sqrtN; n += p) isnp[n] = true;
      ++pi;
      foreach (l; 1 .. sqrtN + 1) {
        const n = N / l;
        if (n < p^^2) {
          break;
        }
        // pi = #{1, p_1, ..., p_{pi-1}}
        // large[l] -= get(n / p) - pi;
        large0[l] -= (get0(n / p) - get0(p - 1));
        large1[l] -= (get1(n / p) - get1(p - 1)) * p;
        large2[l] -= (get2(n / p) - get2(p - 1)) * p * p;
        large3[l] -= (get3(n / p) - get3(p - 1)) * p * p * p;
      }
      foreach_reverse (n; 1 .. sqrtN + 1) {
        if (n < p^^2) {
          break;
        }
        // pi = #{1, p_1, ..., p_{pi-1}}
        // small[n] -= get(n / p) - pi;
        small0[n] -= (get0(n / p) - get0(p - 1));
        small1[n] -= (get1(n / p) - get1(p - 1)) * p;
        small2[n] -= (get2(n / p) - get2(p - 1)) * p * p;
        small3[n] -= (get3(n / p) - get3(p - 1)) * p * p * p;
      }
    }
  }

  uint getF(int n) {
    uint ret;
    ret += A * (get3(n) - 1);
    ret += B * (get2(n) - 1);
    ret += C * (get1(n) - 1);
    ret += D * (get0(n) - 1);
    return ret;
  }

  debug {
    auto isnp_ = new bool[N + 1];
    foreach (p; 2 .. N + 1) {
      if (!isnp_[p]) {
        for (int n = 2 * p; n <= N; n += p) {
          isnp_[n] = true;
        }
      }
    }
    auto sums = new uint[N + 1];
    foreach (p; 2 .. N + 1) {
      if (!isnp_[p]) {
        sums[p] = A * p^^3 + B * p^^2 + C * p + D;
      }
    }
    foreach (n; 1 .. N + 1) {
      sums[n] += sums[n - 1];
    }
    writeln("sums = ", sums);
    writeln("small0 = ", small0, ", large0 = ", large0);
    writeln("small1 = ", small1, ", large1 = ", large1);
    writeln("small2 = ", small2, ", large2 = ", large2);
    writeln("small3 = ", small3, ", large3 = ", large3);
    foreach (n; 1 .. sqrtN + 1) {
      assert(sums[n] == getF(n));
    }
    foreach_reverse (l; 1 .. sqrtN + 1) {
      assert(sums[N / l] == getF(N / l));
    }
  }

  uint ans;
  for (int a = 1, b; a < N; a = b) {
    const k = N / (a + 1);
    b = N / k;
    // (a, b]: k
    ans += k * (getF(b) - getF(a));
  }
  foreach (p; 2 .. sqrtN + 1) {
    const f = getF(p) - getF(p - 1);
    int n = N / p^^2;
    for (; n >= 1; n /= p) {
      ans += n * f;
    }
  }
  return ans;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const A = readInt();
      const B = readInt();
      const C = readInt();
      const D = readInt();
      const ans = solve(N, A, B, C, D);
      writeln(ans);

    }
  } catch (EOFException e) {
  }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int limit = 20_000;

void main ()
{
	uint n;
	uint a, b, c, d;
	while (readf (" %s %s %s %s %s", &n, &a, &b, &c, &d) > 0)
	{
		auto s = new bool [limit];
		s[] = true;
		s[0] = false;
		s[1] = false;
		for (uint g = 2; g * g < limit; g++)
		{
			if (s[g])
			{
				for (uint e = g; e * g < limit; e++)
				{
					s[e * g] = false;
				}
			}
		}

		uint [] p;
		foreach (g; 0..limit)
		{
			if (s[g])
			{
				p ~= g;
			}
		}

		uint res = 0;
		n += 1;
		auto t = new bool [limit];
		for (uint start = 0; start < n; start += limit)
		{
			uint finish = min (start + limit, n);
			if (start == 0)
			{
				t[] = s[];
			}
			else
			{
				t[] = true;
				foreach (g; p)
				{
					uint lo = (start + g - 1) / g * g;
					while (lo < finish)
					{
						t[lo - start] = false;
						lo += g;
					}
				}
			}
			foreach (i; start..finish)
			{
				if (t[i - start])
				{
					uint cur = a;
					cur = cur * i + b;
					cur = cur * i + c;
					cur = cur * i + d;

					uint mult = 0;
					uint k = n;
					while (k > 0)
					{
						k /= i;
						mult += k;
					}
					res += cur * mult;
				}
			}
		}
		writeln (res);
	}
}


import std.math;
import std.typecons;
import std.algorithm;

alias Tuple!(uint, "sub", ulong, "num") Flowers;

Flowers solve(const uint[] bs) {
	uint miin, maax;
	maax = miin = bs[0];
	foreach (i; 1..bs.length) {
		miin = min(miin, bs[i]);
		maax = max(maax, bs[i]);
	}

	ulong minN = 0;
	ulong maxN = 0;
	foreach (b; bs) {
		if (b == miin) {++minN;}
		if (b == maax) {++maxN;}
	}

	return Flowers(maax - miin, (miin == maax) ? (minN * (minN - 1) / 2) : (minN * maxN));
}

unittest {
	assert(Flowers(1, 1) == solve([1, 2]));
	assert(Flowers(4, 1) == solve([1, 4, 5]));
	assert(Flowers(2, 4) == solve([3, 1, 2, 3, 1]));
	assert(Flowers(0, 1) == solve([1, 1]));
	assert(Flowers(0, 3) == solve([1, 1, 1]));
	assert(Flowers(0, 10) == solve([345, 345, 345, 345, 345]));
}

int main(string[] argv) {
	import std.stdio;

	uint n = 0;
	readf(" %s", &n);
	auto bs = new uint[](n);
	foreach (i; 0..n) {
		readf(" %s", &(bs[i]));
	}
	auto res = solve(bs);
	writeln(res.sub, ' ', res.num);
    return 0;
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    ulong n = readln.chomp.to!ulong;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong t1 = 0;
    ulong t2 = 0;
    foreach(item; b) {
        if(item == b[$-1])
            t1 += 1;
        if(item == b[0])
            t2 += 1;
    }
    //ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong ways = t1*t2;
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    ulong n = readln.chomp.to!ulong;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong ways = (cast(ulong)count(b,b[0]))*(cast(ulong)count(b,b[$-1]));
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;
    b.sort;

    ulong ways = b.filter!(x => x == b[$-1]).count * b.filter!(x => x == b[0]).count;

    writefln("%d %d", b[$-1]-b[0], ways);
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    ulong n = readln.chomp.to!ulong;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong t1 = 0;
    ulong t2 = 0;
    foreach(item; b) {
        if(item == b[$-1])
            t1 += 1;
        if(item == b[0])
            t2 += 1;
    }
    //ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong ways = t1*t2;
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;
    b.sort;

    ulong ways = count(b,b[0])*count(b,b[$-1]);
    int maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;
import std.bigint;

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;
    b.sort;

    BigInt ways = b.filter!(x => x == b[$-1]).count * b.filter!(x => x == b[0]).count;

    writefln("%d %d", b[$-1]-b[0], ways);
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(x => x.to!int).array;
    b.sort;

    int[int] c;

    foreach(item; b) {
        c.update(item,
                {
                return 1;
                },
                (ref int i) {
                return i+1;
                });
    }

    int maxima = b[$-1]-b[0];

    int ways = 0;
    foreach(item; b) {
        //ways += c[item+maxima];
        if(((item+maxima) in c) !is null)
            ways += c[item+maxima];
    }

    writefln("%d %d", maxima, ways);
}

// https://codeforces.com/problemset/problem/459/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(x => x.to!int).array;
    b.sort;

    int[int] c;

    foreach(item; b) {
        c.update(item,
                {
                return 1;
                },
                (ref int i) {
                return i+1;
                });
    }

    int maxima = b[$-1]-b[0];

    int ways = 0;
    foreach(item; b) {
        //ways += c[item+maxima];
        if(((item+maxima) in c) !is null)
            ways += c[item];
    }

    writefln("%d %d", maxima, ways);
}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

void main(){

}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
  assert(solve([1,1,1]) == [0,3],"D");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  if ((p[max] - p[min]) == 0){
    return [0,cnt[p[0]]];
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

void main(){
  int a;
  readf("%s\n",&a);

  int[] x = new int[a];
  for(int i = 0; i< a; i++){
    readf("%s ",x.ptr+i);
  }
  auto s = solve(x);
  writefln("%s %s",s[0],s[1]);
}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
  assert(solve([1,1,1]) == [0,6],"D");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  if ((p[max] - p[min]) == 0){
    return [0,cnt[p[0]]*(cnt[p[0]]-1)];
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

void main(){
  int a;
  readf("%s\n",&a);

  int[] x = new int[a];
  for(int i = 0; i< a; i++){
    readf("%s ",x.ptr+i);
  }
  auto s = solve(x);
  writefln("%s %s",s[0],s[1]);
}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

void main(){
  int a;
  readf("%s\n",&a);

  int[] x = new int[a];
  for(int i = 0; i< a; i++){
    readf("%s ",x.ptr+i);
  }
  auto s = solve(x);
  writefln("%s %s",s[0],s[1]);
}


/+ dub.sdl:
    name "B"
    dependency "dunkelheit" version="1.0.1"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner, dkh.algorithm;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    string s;
    sc.read(s);

    int n = s.length.to!int;

    long r = n;
    long ans = 0;
    foreach_reverse (l; 0..n) {
        int k = 1;
        while (l + 2 * k < r && (s[l + k] != s[l] || s[l + 2 * k] != s[l])) k++;
        r = min(r, l + 2 * k);

        ans += (n - r);
    }

    writeln(ans);
    return 0;
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/algorithm.d */
// module dkh.algorithm;

import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = l + (r-l) / 2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

import std.range.primitives;

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "minimum: range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "maximum: range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() const {
        return now.empty;
    }
    @property auto front() const {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    private File f;

    this(File f) {
        this.f = f;
    }
    private char[512] lineBuf;
    private char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    assert(succW());
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }

    void read(Args...)(auto ref Args args) {
        import std.exception : enforce;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }

    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main(){
    auto S = readln.chomp;
    auto N = S.length.to!int;
    long ans = 1L * N * (N + 1) / 2;

    foreach (l; 0..N) foreach (r; l..min(N, l+10)) {
        bool ok = true;
        foreach (i; l..r+1) for (int j = 1; i - j >= l && i + j <= r; ++j) {
            if (S[i-j] == S[i] && S[i] == S[i+j]) ok = false;
        }
        ans -= ok;
    }

    ans.writeln;
}


import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

enum EPS = 1e-12L;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const L = readReal();
        auto A = new real[N + 2];
        A[0] = 0.0L;
        A[N + 1] = L;
        foreach (i; 1 .. N + 1) {
          A[i] = readReal();
        }

        auto ls = new real[N + 2];
        auto rs = new real[N + 2];
        ls[0] = 0.0L;
        foreach (i; 0 .. N + 1) {
          ls[i + 1] = ls[i] + (A[i + 1] - A[i]) / (1 + i);
        }
        rs[N + 1] = 0.0L;
        foreach_reverse (i; 0 .. N + 1) {
          rs[i] = (A[i + 1] - A[i]) / (N + 1 - i) + rs[i + 1];
        }
        debug {
          writeln("ls = ", ls);
          writeln("rs = ", rs);
        }

        real ans;
        foreach (i; 0 .. N + 1) {
          if (ls[i] <= rs[i] + EPS && ls[i + 1] + EPS >= rs[i + 1]) {
            const real u = 1 + i;
            const real v = N + 1 - i;
            const d = A[i + 1] - A[i];
            ans = (d + u * ls[i] + v * rs[i + 1]) / (u + v);
            break;
          }
        }
        writefln("%.12f", ans);
      }
    }
  } catch (EOFException e) {
  }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { y.modpow(mod - 2); x.modm(y); }

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 0.0000001)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

void main()
{
	auto t = RD!int;
	auto ans = new double[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto l = RD!int;
		auto a = RDA;

		bool f(double x)
		{
			double pos1 = 0.0, pos2 = l;
			{
				long last;
				double time = x;
				double sp = 1.0;
				foreach (i; 0..n)
				{
					auto d = a[i] - last;
					if (time*sp <= d) break;
					time -= d / sp;
					last = a[i];
					pos1 = last;
					sp += 1.0;
				}
				pos1 += time * sp;
			}
			{
				long last = l;
				double time = x;
				double sp = 1.0;
				foreach_reverse (i; 0..n)
				{
					auto d = last - a[i];
					if (time*sp <= d) break;
					time -= d / sp;
					last = a[i];
					pos2 = last;
					sp += 1.0;
				}
				pos2 -= time * sp;
			}
			debug writeln("time:", x, " pos1:", pos1, " pos2:", pos2);
			return pos1 >= pos2;
		}

		auto r = binarySearch!(f)(cast(double)l, 0.0);
		ans[ti] = r;
	}

	foreach (e; ans)
	{
		writefln(FMT_F, e);
	}
	stdout.flush;
	debug readln;
}


import std.stdio;

void main(){
  int n,m; readf("%d\n%d\n",&n,&m); bool can=true;
  while (n--){
    int a,b; readf("%d %d\n",&a,&b);
    if (m!=a && m!=b && m!=7-a && m!=7-b) m=7-m; else can=false;
  }
  writeln(can? "YES": "NO");
}

import std.stdio, std.string, std.algorithm;
import std.conv, std.array;
import std.container;
import std.typecons;

void main() {
    int n; readf("%d\n", &n);
    int t; readf("%d\n", &t);
    for (int i = 0; i < n; i++) {
        int a, b; readf("%d %d\n", &a, &b);
        bool[] u = new bool[6];
        u[t - 1] = true;
        u[a - 1] = u[7 - a - 1] = true;
        u[b - 1] = u[7 - b - 1] = true;
        if (u.count!"a == false" > 1) {
            writeln("NO");
            return;
        }
    }
    writeln("YES");
}

import std.stdio;

void main() {
    uint n, s;
    readf("%d %d", &n, &s);
    for (uint i = 0; i < n; ++i) {
    	uint a, b;
    	readf(" %d %d", &a, &b);

    	if (s != a && s != 7 - a && s != b && s != 7 - b) {

    	}
    	else {
    	    writeln("NO");
    	    return;
    	}
    }
    writeln("YES");
}

import std.string;
import std.stdio;
import std.conv;

int main() {

    int other(int[] a) {
        int[int] set;
        foreach(int i; a)
            set[i] = 1;
        for (int i = 1; i <= 6; ++i)
            if ((i in set) is null)
                return i;
        return 1;
    }

    auto n = to!int(strip(readln()));
    auto x = to!int(strip(readln()));
    auto a = new int[n];
    auto b = new int[n];
    for (int i = 0; i < n; ++i) {
        auto tmp2 = split(strip(readln()), " ");
        a[i] = to!int(tmp2[0]);
        b[i] = to!int(tmp2[1]);
    }
    int[] h = [a[0], b[0], 7 - a[0], 7 - b[0], x];
    h ~= other(h);
    for (int i = 1; i < n; ++i) {
        int[int] set = [a[i] : 1, b[i] : 1, 7 - a[i] : 1, 7 - b[i] : 1];
        if ((h[5] in set) is null)
            h = set.keys ~ other(set.keys ~ h[5]) ~ h[5];
        else {
            writeln("NO");
            return 0;
        }
    }
    writeln("YES");
    return 0;
}

import std.stdio;

void main(){
  int n,m; readf("%d\n%d\n",&n,&m);
  bool[int] can; can[7-m]=true;
  while (n--){
    int a,b; readf("%d %d\n",&a,&b);
    bool[int] could;
    foreach (i; can)
      if (i!=a && i!=b && i!=7-a && i!=7-b)
        could[7-i]=true;
    can=could;
  }
  writeln(can.length==1? "YES": "NO");
}