#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
    int N;
    map<ll, int> mp;
    cin >> N;
    for (int i = 0; i < N; i++) {
        ll A;
        cin >> A;
        mp[A]++;
    }
    int ans = 0;
    for (auto ite = mp.rbegin(); ite != mp.rend(); ++ite) {
        if (ite->second == 0) continue;

        ll x = pow(2, floor(log2(ite->first)) + 1);
        auto ite1 = mp.lower_bound(x - ite->first);

        if (ite1->first + ite->first == x) {
            if (ite1->first == ite->first) {
                int c = ite->second / 2;
                ite->second -= c;
                ite1->second -= c;
                ans += c;
            } else {
                int c = min(ite->second, ite1->second);
                ite->second -= c;
                ite1->second -= c;
                ans += c;
            }
        }
    }
    cout << ans << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n)  for(long long i=0;i<(long long)(n);i++)
#define REP(i,k,n) for(long long i=k;i<(long long)(n);i++)
#define all(a) a.begin(),a.end()
#define pb push_back
#define eb emplace_back
#define lb(v,k) (lower_bound(all(v),k)-v.begin())
#define ub(v,k) (upper_bound(all(v),k)-v.begin())
#define fi first
#define se second
#define pi M_PI
typedef long long ll;
typedef pair<ll,ll> P;
typedef tuple<ll,ll,ll> PP;
typedef multiset<ll> S;
typedef priority_queue<ll> PQ;
typedef priority_queue<P,vector<P>,greater<P>> SPQ;
using vi=vector<ll>;
using vvi=vector<vi>;
using vvvi=vector<vvi>;
using vp=vector<P>;
using vvp=vector<vp>;
using vb=vector<bool>;
const ll inf=1001001001001001;
const int INF=1001001001;
const int mod=1000000007;
template<class T> bool chmin(T&a,T b){if(a>b){a=b;return true;}return false;}
template<class T> bool chmax(T&a,T b){if(a<b){a=b;return true;}return false;}
template<class T> void out(T a){cout<<a<<'\n';}
template<class T> void outp(T a){cout<<'('<<a.fi<<','<<a.se<<')'<<'\n';}
template<class T> void outvp(T v){rep(i,v.size())outp(v[i]);}
template<class T> void outv(T v){rep(i,v.size()){if(i)cout<<' ';cout<<v[i];}cout<<'\n';}
template<class T> void outvv(T v){rep(i,v.size()){rep(j,v[i].size()){if(j)cout<<' ';cout<<v[i][j];}cout<<'\n';}}
ll gcd(ll a,ll b){if(b==0)return a;return gcd(b,a%b);}
ll modpow(ll a,ll b){a%=mod;if(b==0)return 1;if(b&1)return a*modpow(a,b-1)%mod;ll k=modpow(a,b/2);return k*k%mod;}

int main(){
    ll n,ans=0;cin>>n;
    multiset<ll> v;
    rep(i,n){
        ll a;cin>>a;
        v.insert(a);
    }
    while(!v.empty()){
        auto it=v.end();
        it--;
        ll k=1;
        while(k<=*it)k*=2;
        k=k-*it;
        v.erase(it);
        auto w=v.lower_bound(k);
        if(*w==k){
            ans++;
            v.erase(w);
        }
    }
    out(ans);
}


#include <iostream>
#include <cstdio>
#include <string>
#include <sstream>
#include <algorithm>
#include <math.h>
#include <map>
#include <iomanip>
#include <vector>
#include <queue>
#include <set>

#define PI 3.14159265359

#define INF 99999999;

#define rep(i, n) for(int i=0; i<n; i++)
#define REP(n) rep(i, n)

typedef long long ll;

using namespace std;

/*
class LightSwitchingPuzzle
{
public:
	int minFlips(string s)
	{

	}
}
*/

int main()
{
	int n, m;

	while (cin >> n >> m, n | m)
	{
		int p[n];

		REP(n) cin >> p[i];
		sort(p, p + n);

		int sum = 0, cnt = 0;
		for (int i=n-1; i>=0; i--)
		{
			cnt++;
			if (cnt == m)
			{
				cnt = 0;
				continue;
			}
			sum += p[i];
		}

		cout << sum << endl;

		/*
		//テスト出力
		REP(n) cout << p[i] << " ";
		*/
	}

	return 0;
}

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <sstream>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

#define rep(i, n) for(int i = 0; i < n; i ++)
#define COUNT(i, n) for(int i = 1; i <= n; i ++)
#define ITER(c) __typeof((c).begin())
#define each(c, it) for(ITER(c) it =(c).begin(); it!=(c).end(); it++)
#define ALL(c) c.begin(), c.end()
#define mp make_pair
#define pb push_back
#define MEMSET(v, h) memset((v), h, sizeof(v))

using namespace std;

typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;
typedef vector<string> vs;

const int INF = 1 << 24;

int main(void){
    for(int n, m, s; s = 0, cin >> n >> m, n; cout << s << endl){
        priority_queue<int> p;
        rep(i, n){
            int in; cin >> in;
            p.push(in);
        }
        COUNT(i, n){
            if(i % m) s += p.top();
            p.pop();
        }
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define FOR(i,a,b) for(int i=(a); i<=(b); i++)
#define rep(i,n) for(int i = 0; i < (n); i++)
#define chmin(a,b) if((a)>(b)) (a)=(b);
#define chmax(a,b) if((a)<(b)) (a)=(b);
#define vi vector<int>
#define pii pair<int,int>
#define all(v) (v).begin(),(v).end()
#define allr(v) (v).rbegin(),(v).rend()
#define pb push_back
#define pf push_front
int gcd(int a,int b){/*a>=0,b>=0,￢(a=b=0)*/
  while(min(a,b)>0){if(a<b)swap(a,b);a%=b;}return max(a,b);
}
int dx[]={1,0,-1,0,1,-1,-1,1};
int dy[]={0,1,0,-1,1,1,-1,-1};
const int MOD = 1e9+7;
const long long INF = 1e18+10;

/*--------------------------------------------------------------------*/
signed main(){
	int n;
	cin>>n;
	int a[17];
	int x[17][17];
	int y[17][17];
	rep(i,n){
		cin>>a[i];
		rep(j,a[i]){
			cin>>x[i][j]>>y[i][j];
		}
	}
	int ans=0;
	rep(bit,1<<n){
		int shoujiki[17];
		rep(i,n){
			if(bit&(1<<i)) shoujiki[i]=1;
			else shoujiki[i]=0;
		}
		int to[17][17];
		int ok=1;
		rep(i,n){
			if(shoujiki[i]){
				rep(j,a[i]){
					if(y[i][j]){
						if(shoujiki[x[i][j]-1]==0) ok=0;
					}else{
						if(shoujiki[x[i][j]-1]==1) ok=0;
					}

				}
			}
		}
		if(ok){
			int cnt=0;
			rep(i,n){
				if(shoujiki[i]==1) cnt++;
			}
			chmax(ans,cnt);
		}
	}

	cout<<ans<<endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL MOD=1000000007;

LL nol[60],satu[60];

int main(){
	ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
	int n;
	LL a;
	cin >> n;
	for(int i=1;i<=n;i++){
		cin >> a;
		for(int j=0;j<60;j++){
			if(a & (1LL<<j))satu[j]++;
			else nol[j]++;
		}
	}
	LL ans=0;
	for(int i=0;i<60;i++){
		LL byk=(nol[i]*satu[i])%MOD,res=((1LL<<i))%MOD;
		ans=(ans+((byk*res)%MOD))%MOD;
	}
	cout << ans << '\n';
	return 0;
}


#pragma region header
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define rev(i, n) for(int i = (int)(n - 1); i >= 0; i--)
#define rev1(i, n) for(int i = (int)(n); i > 0; i--)
#define pb push_back
#define all(v) (v).begin(), (v).end()
#define resort(v) sort((v).rbegin(), (v).rend())
#define vi vector<int>
#define vvi vector<vector<int>>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
using ll = long long;
using P = pair<int, int>;
/* ----------------よく使う数字や配列----------------- */
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
constexpr ll mod = 1e9+7;
constexpr ll inf = INT32_MAX/2;
constexpr ll INF = LLONG_MAX/2;
constexpr long double eps = DBL_EPSILON;
constexpr long double pi = 3.141592653589793238462643383279;
/* ----------------------end----------------------- */

/* --------------------テンプレート------------------ */
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
/* ----------------------end----------------------- */

/* --------------------ライブラリ-------------------- */
ll fact(int i) {       //階乗
    if (i == 0) return 1;
    return (fact(i - 1)) * i % mod;
}
ll gcd(ll a, ll b) {        //最大公約数
    if(b == 0) return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b) {      //最小公倍数
    return a * b / gcd(a, b);
}
int keta(ll n) {        //桁数を求める
    if(n == 0) return 1;
    int count = 0;
    while(n != 0) {
        n /= 10;
        count++;
    }
    return count;
}
ll ketasum(ll n) {    //各桁の和
    ll sum = 0;
    while(n != 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
/* ----------------------end----------------------- */
#pragma endregion
signed main() {
    int h,w;cin >> h >> w;
    vvb bo(h,vb(w));
    vector<P> v;
    rep(i, h) {
        rep(j, w) {
            char c;cin >> c;
            if(c=='#') {
                bo[i][j]=true;
                v.pb({i,j});
            }
            else bo[i][j]=false;
        }
    }
    bool ok = true;
    rep(i, v.size()) {
        rep(j, 4) {
            int x=v[i].first+dx[j],y=v[i].second+dy[j];
            if(x<0||x>=h||y<0||y>=w||!bo[x][y]) {
                // cout << i << endl;
                if(j==3) {
                    cout << "No" << endl;
                    return 0;
                }
                continue;
            }
            break;
        }
    }
    cout << "Yes" << endl;
    return 0;
}

#include <bits/stdc++.h>
#define ri register
#define int long long
using namespace std; const int N=200010;
inline int read()
{
    int s=0, w=1; ri char ch=getchar();
    while(ch<'0'||ch>'9') { if(ch=='-') w=-1; ch=getchar(); }
    while(ch>='0'&&ch<='9') s=(s<<3)+(s<<1)+(ch^48), ch=getchar();
    return s*w;
}
int h,w;
char s[60][60];
signed main()
{
    h=read(), w=read();
    for(ri int i=1;i<=h;i++) scanf("%s",s[i]+1);
    for(ri int i=1;i<=h;i++)
    for(ri int j=1;j<=w;j++)
    if(s[i][j]=='#')
    {
        if(s[i-1][j]!='#'&&s[i+1][j]!='#'&&s[i][j-1]!='#'&&s[i][j+1]!='#')
        {
            puts("No");
            return 0;
        }
    }
    puts("Yes");
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

//Made with <3 by MinumCoklatPanas
typedef long long ll;
const ll INF = 1e9;
const ll INFF = 1e18;
const ll MAXN = 510;
const ll MOD = 1e9 + 7;
const double PI = acos(-1.0);
const double INFD = 1E9;
const double EPS = 1e-9;

ll mul(ll x,ll y)
{
    return ((x % MOD) * (y % MOD)) % MOD;
}

ll add(ll x,ll y)
{
    return ((x % MOD) + (y % MOD)) % MOD;
}

ll sub(ll x,ll y)
{
    ll ret = ((x % MOD) - (y % MOD)) % MOD;
    if (ret < 0)
        ret += MOD;
    return ret;
}

ll modpow(ll x,ll y)
{
    if (!y) return 1;
    ll z = modpow(x,y / 2);
    z = mul(z,z);
    if (y & 1) z = mul(z,x);
    return z;
}

ll inv(ll x)
{
    return modpow(x,MOD - 2);
}

ll bagi(ll x,ll y)
{
    return mul(x,inv(y));
}

ll pref[65][300010];
ll tab[300010];

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    ll n;
    cin >> n;
    for (ll i = 1 ; i <= n ; i++)
    {
        for (ll j = 0 ; j < 60 ; j++)
            pref[j][i] = pref[j][i - 1];
        ll ta;
        cin >> ta;
        for (ll j = 0 ; j < 60 ; j++) if (ta & (1ll << j))
        {
            pref[j][i]++;
        }
        tab[i] = ta;
    }
    ll ans = 0;
    for (ll i = 1 ; i <= n ; i++)
    {
        ll pengali = 1;
        ll rem = n - i;
        for (ll j = 0 ; j < 60 ; j++)
        {
            ll satu = pref[j][n] - pref[j][i];
            ll nol = rem - satu;
            // cout << j << ": " << satu << " " << nol << endl;
            if (tab[i] & (1ll << j))
                ans = add(ans,mul(nol,pengali));
            else
            {
                // cout << "yo\n";
                ans = add(ans,mul(satu,pengali));
            }
            pengali = mul(pengali,2ll);
        }
        // cout << ans << endl;
    }
    cout << ans << endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

#define IOS             ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define read            freopen("in.txt","r",stdin)
#define write           freopen("out.txt","w",stdout)
#define loop(i,a,b)     for (ll i = a; i <= b; i++)
#define rloop(i,a,b)    for (ll i = a; i >= b; i--)
#define ms(a,x)         memset(a,x,sizeof a)
#define ll              long long int
#define ff              first
#define ss              second
#define all(a)          a.begin(),a.end()
#define rall(a)         a.rbegin(),a.rend()
#define pb              push_back
#define nl              cout<<"\n"
#define gcd(a,b)        __gcd((a),(b))
#define lcm(a,b)        ((a)*(b))/(gcd(a,b))
#define sq(a)           (a)*(a)
#define sz(a)           a.size()
#define mod             1000000007
#define PI              2*acos(0.0)

int main()
{
    IOS
    int T=1;
    //cin>>T;
    while(T--)
    {
        ll n;
        cin>>n;
        ll a[n];
        loop(i,0,n-1) cin>>a[i];
        ll res=0;
        loop(i,0,60)
        {
            ll one=0,zero=0;
            loop(j,0,n-1)
            {
                if(a[j] & 1ll<<i) one++;
                else zero++;
            }
            res=((res)+(1ll<<i)%mod*one%mod*zero%mod)%mod;
        }
        cout<<res;

    }
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<complex>
#define rep(i, a, n) for(int i=a;i<n;i++)
#define REP(i, n) rep(i, 0, n)
#define repb(i, a, b) for(int i = a; i >= b; i--)
#define all(a) a.begin(), a.end()
#define int long long
#define R long double
#define P complex<R>
using namespace std;
const int mod = 1000000007;
const int INF = 1e12;
template<class T>bool chmax(T &a, const T &b) { return (a < b) ? (a = b, 1) : 0;}
template<class T>bool chmin(T &a, const T &b) { return (b < a) ? (a = b, 1) : 0;}
const R PI = acos(-1.0L);
const R inf = 1e13;
int x[110], y[110];
R ans[110];
inline R dist(int i, P q) {
   P p = P(x[i], y[i]);
   return norm(p - q);
}
signed main(){
    int n;
    cin>>n;
    for (int i=0;i<n;i++)
	{
		cin>>x[i]>>y[i];
    }
    int limit = 200000;
    rep(i, 0, limit){
        R cur = 2.0 * PI / limit * i;
        P point = polar(inf, cur);
        R d = 1e130;
        int idx = -1;
        rep(j, 0, n) if(chmin(d, dist(j, point))) idx = j;
        ans[idx] += 1.0;
    }
    cout.precision(20);
	rep(i, 0, n) cout << fixed << 1.0 * ans[i] / limit << endl;
	return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <string>
#include <stdlib.h>
#include <fstream>
#include <set>
#include <map>
#include <stack>
#include <deque>
#include <iterator>
#include <iomanip>
#include <queue>
using namespace std;

int main(){
    long long n;
    cin >> n;
    vector<vector<long long> > a(n + 1, vector<long long>(n));
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j < n; ++j){
            cin >> a[i][j];
        }
    }
    vector<long long> round;
    vector<long long> cnt(n + 1, 1);
    for(int i = 1; i <= n; ++i){
        if(a[a[i][1]][1] == i){
            round.push_back(i);
        }
    }
    long long ans = 0;
    while(!round.empty()){
        ans++;
        vector<long long> nw;
        for(long long i: round){
            cnt[i]++;
            if(cnt[i] <= n - 1){
                long long x = a[i][cnt[i]];
                if(i == a[x][cnt[x]]){
                    nw.push_back(i);
                    nw.push_back(x);
                }
            }
        }
        round = nw;
    }
    for(int i = 1; i <= n; ++i){
        if(cnt[i] != n){
            cout << -1;
            return 0;
        }
    }
    cout << ans;
}


#include <bits/stdc++.h>
// iostream is too mainstream
#include <cstdio>
// bitch please
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <cmath>
#include <iomanip>
#include <time.h>
#define dibs reserve
#define OVER9000 1234567890
#define ALL_THE(CAKE,LIE) for(auto LIE =CAKE.begin(); LIE != CAKE.end(); LIE++)
#define tisic 47
#define soclose 1e-8
#define chocolate win
// so much chocolate
#define patkan 9
#define ff first
#define ss second
#define abs(x) (((x) < 0)?-(x):(x))
#define uint unsigned int
#define dbl long double
#define pi 3.14159265358979323846
using namespace std;
// mylittledoge

using cat = long long;

#ifdef DONLINE_JUDGE
	// palindromic tree is better than splay tree!
	#define lld I64d
#endif

cat pw(cat a, cat e, cat mod) {
	if(e <= 0) return 1;
	cat x = pw(a, e/2, mod);
	x = x * x % mod;
	if(e&1) x = x * a % mod;
	return x;
}

int main() {
	cin.sync_with_stdio(0);
	cin.tie(0);
	cout << fixed << setprecision(10);
	int N, M;
	cin >> N >> M;
	cat tot = 1, dif = 0, fac_inv = 1, mod = 998244353;
	for(int i = 1; i < N; i++) {
		tot = tot * (3*M+i) % mod;
		fac_inv = fac_inv * i % mod;
	}
	vector<cat> prod_m1(N+3*M+1, 0), prod_m2(N+3*M+1, 0);
	prod_m1[0] = fac_inv;
	prod_m2[0] = fac_inv * pw(N-1, mod-2, mod) % mod;
	for(int i = 0; i < M; i++) {
		prod_m1[i+1] = prod_m1[i] * (i+N) % mod * pw(i+1, mod-2, mod) % mod;
		prod_m2[i+1] = prod_m2[i] * (i+N-1) % mod * pw(i+1, mod-2, mod) % mod;
	}
	for(int i = 0; i < M; i++) dif = (dif + prod_m2[i]) % mod;
	dif = dif * N % mod * (N-1) % mod;
	vector<cat> C(N+1, 0); // C(N, i)
	C[0] = 1;
	for(int i = 1; i <= N; i++) C[i] = C[i-1] * pw(i, mod-2, mod) % mod * (N-i+1) % mod;
	for(int i = M+1; i <= min(3*M, N); i++) if((M-i)%2 == 0)
		dif = (dif + prod_m1[(3*M-i)/2] * C[i]) % mod;
	cat ans = (tot - dif) * pw(fac_inv, mod-2, mod) % mod;
	if(ans < 0) ans += mod;
	cout << ans << "\n";
	return 0;
}

// look at my code
// my code is amazing

#include<stdio.h>
#include<string.h>
#define it register int
#define ct const int
#define il inline
using namespace std;
typedef long long ll;
#define rll register ll
#define cll const ll
#define P 998244353
const int N=305;
int f[N][N][N],K,ans,n,cn[N];
char s[N];
il void mo(it&p,ct q){p+=q,p=(p>=P?p-P:p);}
int main(){
	scanf("%s%d",s+1,&K),n=strlen(s+1),K=(K<n?K:n);it i,j,k,l,c0;
	for(i=1;i<=n;++i) s[i]=='0'?++c0:++cn[c0];
	f[0][0][0]=1;
	for(i=0;i<=c0;++i)
		for(j=0;j<=K;++j)
			for(k=0;k<=j;++k)
				for(l=-(k<cn[i]?k:cn[i]);l<=K-j;++l)
					mo(f[i+1][j+(l>0?l:0)][k+l],f[i][j][k]);
	for(i=0,++c0;i<=K;++i) ans+=f[c0][i][0],ans=(ans>=P?ans-P:ans);
	printf("%d",ans);
	return 0;
}


#include<iostream>
#include<algorithm>
#include<functional>

int *v,m,n,ans=0;

int main(){
	while(true){
		std::cin >> n >> m;
		if(!n && !m)
			return 0;
		v = new int[n];
		for(int i=0 ;i<n; i++)
			std::cin >> v[i];
		std::sort(v,v+n,std::greater<int>());
		if(m!=1)
			for(int i=0; i<n; i++)
				if(!((i+1)%m == 0 && (i+1) >= m))
					ans += v[i];
		std::cout << ans << std::endl;
		delete[] v;
		ans = 0;
	}
}

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
	int m, n;
	while (cin >> n >> m&&n != 0 && m != 0) {
		int a = n%m, b = (n - a) / m, d = 0, e[1000], sum = 0;
		string c, h = "";
		getline(cin, c);
		getline(cin, c);
		c += " ";
		for (int i = 0; i < c.length(); i++) {
			if (c[i] == ' ') {
				e[d] = atoi(h.c_str());
				h = "";
				d++;
			}
			else
				h += c[i];
		}
		sort(e, e + n);
		d = 0;
		for (int i = 0; i < a; i++) {
			sum += e[i];
			d++;
		}
		for (int i = 0; i < b; i++) {
			for (int j = 0; j < m; j++) {
				if (j != 0) {
					sum += e[i*m + j+a];
				}
			}
		}
		cout << sum << endl;
	}
}


#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <functional>

using namespace std;

typedef pair<double, string> P;
typedef pair<string, double> Q;

int main() {
	int n;
	while (cin >> n) {
		if (n == 0) {
			break;
		}
		string plant;
		int p, a, b, c, d, e, f, s, m;
		int time;
		double kou;
		priority_queue<P> pq;
		for (int i = 0; i < n; i++) {
			cin >> plant >> p >> a >> b >> c >> d >> e >> f >> s >> m;
			time = a+b+c+(d+e)*m;
			kou = (double)(s*f*m-p) / (double)time;
			P pp;
			pp.first = kou;
			pp.second = plant;
			pq.push(pp);
		}
		while (!pq.empty()) {
			P ppp = pq.top();
			pq.pop();
			priority_queue< Q, vector<Q>, greater<Q> > pqq;
			Q q;
			q.first = ppp.second;
			q.second = ppp.first;
			pqq.push(q);
			while (!pq.empty()) {
				if ((pq.top()).first == ppp.first) {
					q.first = (pq.top()).second;
					pqq.push(q);
					pq.pop();
				} else {
					break;
				}
			}
			while (!pqq.empty()) {
				cout << (pqq.top()).first << endl;
				pqq.pop();
			}
		}
		cout << '#' << endl;
	}
	return 0;
}

#include<bits/stdc++.h>
using namespace std;

int N;
const double EPS = 1e-10;

struct state{
  string name;
  double k;
  state(){}
  state(int P,int A,int B,int C,int D, int E,int F,int S,int M){
    int time = A + B + C + (D + E)*M;
    int num = M * F;
    int mon = num * S;
    int s = mon - P;
    k = (double)s/(double)time;
  }
  bool operator<(const state& st) const {
    return abs(k-st.k) < EPS ? name < st.name : k > st.k;
  }
};

state st[111];
int main(){
  while( cin >> N && N ){
    for(int i=0;i<N;i++){
      string L;int P,A,B,C,D,E,F,S,M;
      cin >> L >> P >> A >> B >> C >> D >> E >> F >> S >> M;
      st[i] = state(P,A,B,C,D,E,F,S,M);
      st[i].name = L;

    }
    sort(st,st+N);
    for(int i=0;i<N;i++)
      cout << st[i].name << endl;
    cout << "#" << endl;
  }
}


#if 1
  #include <bits/stdc++.h>
#else
  #include "../../bits/stdc++.h"
#endif

#define FOR(i,a,b) for(int i = (a);i < (b);i++)
#define RFOR(i,a,b) for(int i = (b)-1;i >= (a);i--)
#define REP(i,n) FOR(i,0,(n))
#define RREP(i,n) RFOR(i,0,(n))

using namespace std;

typedef pair<int, int> P;
#define pb push_back
#define mp make_pair
#define ft first
#define sd second

int m, nin, nax;
int p[202];

bool input(){
  cin>>m>>nin>>nax;
  REP(i, m)cin>>p[i];
  return m;
}

void solve(){
  int s=0, b=0;
  FOR(i, nin-1, nax) {
    if(p[i]-p[i+1]>=s){
      b=i+1;
      s=p[i]-p[i+1];
    }
  }
  cout<<b<<endl;
}

int main(){
  cin.tie(0);

  while (input()){
      solve();
  }

  return 0;
}

#include<bits/stdc++.h>

using namespace std;

int main(){
    int m,n_min,n_max;
    while(cin>>m>>n_min>>n_max,m){
        int pre;
        for(int i=0;i<n_min;++i){
            cin>>pre;
        }
        int buf1=0,ans;
        for(int i=n_min;i<=n_max;++i){
            int p;cin>>p;
            if(buf1<=pre-p){
                buf1=pre-p;
                ans=i;
            }
            pre=p;
        }
        for(int i=n_max+1;i<m;++i)cin>>pre;
        cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
typedef long long ll;
typedef vector<vector<int>> vv;
typedef pair<int, int> P;
typedef tuple<int, int, int> tp;

// input
int N, Q;
vector<tp> XST;
vector<int> D;

vector<int> ans;
set<P> ds;

void input() {
    cin >> N >> Q;
    XST = vector<tp>(N);
    rep(i, N) {
        int s, t, x;
        cin >> s >> t >> x;
        XST[i] = tp(x, s, t);
    }
    D = vector<int>(Q);
    rep(i, Q) cin >> D[i];
}

int main() {
    input();
    sort(XST.begin(), XST.end());
    rep(i, Q) ds.insert(P(D[i], i));
    ans = vector<int>(Q, -1);
    rep(i, N) {
        int x, s, t;
        tie(x, s, t) = XST[i];
        auto itr = ds.lower_bound(P(s - x, 0));
        while (itr != ds.end()) {
            if (itr->first >= t - x) break;
            ans[itr->second] = x;
            ds.erase(itr++);
        }
    }
    rep(i, Q) printf("%d\n", ans[i]);
}

// 0514 Quality Checking (????????????)
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0514
// by Equim on 16-12-21

#include <cstdio>

int main()
{
    while (true)
    {
        // INPUT
        int a, b, c, Cases;
        scanf("%d%d%d", &a, &b, &c);
        if (a == 0)
            break;
        scanf("%d", &Cases);

        int Result[a + b + c + 1];
        for (int i = 1; i <= a + b + c; i++)
        {
            Result[i] = 2;
        }

        int RawData[Cases][4];
        for (int i = 0; i < Cases; i++)
        {
            scanf("%d%d%d%d", &RawData[i][0], &RawData[i][1], &RawData[i][2], &RawData[i][3]);
        }

        int Unqualified, QualifiedCount;
        bool HasNewChecked = false;

        // PROCESS
        do
        {
            HasNewChecked = false;

            for (int i = 0; i < Cases; i++)
            {
                if (RawData[i][0] + RawData[i][1] + RawData[i][2] == 0)
                    continue;

                if (RawData[i][3] == 1)
                {
                    for (int j = 0; j <= 2; j++)
                    {
                        Result[RawData[i][j]] = 1;
                        RawData[i][j] = 0;
                    }
                    HasNewChecked = true;
                }
                else
                {
                    Unqualified = 0;
                    QualifiedCount = 0;
                    for (int j = 0; j <= 2; j++)
                    {
                        if (Result[RawData[i][j]] == 1 || RawData[i][j] == 0)
                        {
                            RawData[i][j] = 0;
                            QualifiedCount++;
                        }
                        else
                            Unqualified = j;
                    }
                    if (QualifiedCount == 2)
                    {
                        Result[RawData[i][Unqualified]] = 0;
                        RawData[i][Unqualified] = 0;
                        HasNewChecked = true;
                    }
                }
            }
        } while (HasNewChecked);

        // OUTPUT
        for (int i = 1; i < a + b + c + 1; i++)
        {
            printf("%d\n", Result[i]);
        }
    }
    return 0;
}


#include<iostream>
#include<cstring>

int field[14][14];

void dfs(int r,int c);

int main()
{
	int num;
	char buf[14];
	while(1)
	{
		num=0;
		memset(field,0,sizeof(field));
		for(int i=1;i<=12;i++)
		{
			if(std::cin.eof())break;
			std::cin.getline(buf,14);
			if(buf[0]=='\0')
			{
				i--;
				continue;
			}
			for(int j=1;j<=12;j++)
			{
				field[i][j]=buf[j-1]-'0';
			}
		}
		if(std::cin.eof())break;

		for(int i=1;i<=12;i++)
		{
			for(int j=1;j<=12;j++)
			{
				if(field[i][j]==1)
				{
					dfs(i,j);
					num++;
				}
			}
		}
		std::cout<<num<<std::endl;
	}
	return 0;
}

void dfs(int r,int c)
{
	field[r][c]=0;
	if(field[r-1][c]==1){dfs(r-1,c);}
	if(field[r+1][c]==1){dfs(r+1,c);}
	if(field[r][c-1]==1){dfs(r,c-1);}
	if(field[r][c+1]==1){dfs(r,c+1);}
}

#include<bits/stdc++.h>
using namespace std;

typedef long long int lli;
typedef unsigned long long int ulli;
typedef pair<int,int> pii;
typedef priority_queue< int, vector< int >, greater< int > >  minHeap;

#define ones(x) __builtin_popcount(x)
#define onesl(x) __builtin_popcountl(x)
#define onesll(x) __builtin_popcountll(x)

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define scn(n) scanf("%d",&n)
#define scnll(n) scanf("%lld",&n)
#define scn2(n,m) scanf("%d%d",&n,&m)
#define scn3(n,m,w) scanf("%d%d%d",&n,&m,&w)
#define scn2ll(n,m) scanf("%lld%lld",&n,&m)
#define atoz(v) v.begin(),v.end()
#define ratoz(v) v.rbegin(),v.rend()
#define Fill(a,v) memset(a,v,sizeof(a))
#define fi first
#define se second
#define inf 1e9
#define pi acos(-1.0)
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define mod 1000000007
#define FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define bug(x) cerr << __LINE__ << " says: " << #x << " = " << (x) << "\n"

int Set(int N,int pos)
{
    return N=N | (1<<pos);
}
int reset(int N,int pos)
{
    return N = N & ~(1<<pos);
}
bool check(int N,int pos)
{
    return (bool)(N & (1<<pos));
}

inline int addmod(lli x,lli y)
{
    return (x%mod + y%mod)%mod;
}
inline int submod(lli x,lli y)
{
    return (x%mod - y%mod + mod)%mod;
}
inline int mulmod(lli x,lli y)
{
    return (x%mod * y%mod)%mod;
}

inline int nextSubMask(int i, int mask)
{
    return (i-1)&mask;   /// returns next  submask
}

template<typename T>
void we_r_done(T mssg)
{
    cout<<mssg;
    exit(0);
}

int main()
{
    ///freopen("output.txt","w",stdout);
  // freopen("input.txt","r",stdin);
    FastIO;

    string s;
    while(cin>>s){
        int n = s.size();
        lli ans = 1 + n*1LL*(n-1)/2;
        vector<int>cnt(30,0);
        for(int i=0; i<n; i++){
            cnt[s[i]-'a']++;
        }
        for(int i=0; i<26; i++) ans -= cnt[i]*1LL*(cnt[i]-1)/2;

        cout<<ans<<endl;
    }

    return 0;
}

///sin and cos expect input in radians not degrees. so use , sin(degrees * pi / 180)
///using bs = bitset<MX>; // how many distinct number can be form?
///sort(atoz(v), [](const data x, const data y){return (x.a==y.a?x.b>y.b : x.a<y.a);});


#include<bits/stdc++.h>
using namespace std;
using pii = pair<int,int>;
using ll = long long;
using pll = pair<ll,ll>;
using pli = pair<ll,int>;
using pil = pair<int,ll>;
using ld = long double;
using ui = unsigned int;
using ull = unsigned long long;
using ui128 = __uint128_t;
#define all(x) (x).begin(),(x).end()
#define mp make_pair
#define lc ind<<1
#define rc ind<<1|1
const int MN = 1e5 + 2, LOG = 17, INF = 1e8;
char s[MN];
int wot[MN];
int main () {
	int n;
	scanf ("%d",&n);
	auto nxt = [&] (int a) {int x = a + 1; return x > n ? 1 : x;};
	auto lst = [&] (int a) {int x = a - 1; return x < 1 ? n : x;};
	scanf ("%s",s+1);
	for (int a = 0; a < 2; a++) {
		for (int b = 0; b < 2; b++) {
			wot[1] = a; wot[2] = b;
			for (int i = 3; i <= n; i++) {
				if ((s[i-1] == 'o' && wot[i-1] == 0) || (s[i-1] == 'x' && wot[i-1] == 1)) wot[i] = wot[i-2];
				else wot[i] = wot[i-2] ^ 1;
			}
			bool ok = 1;
			for (int i = 1; i <= n; i++) {
				if ((s[i] == 'o' && wot[i] == 0) || (s[i] == 'x' && wot[i] == 1)) ok &= wot[nxt(i)] == wot[lst(i)];
				else ok &= wot[nxt(i)] != wot[lst(i)];
			}
			if (ok) {
				for (int i = 1; i <= n; i++) putchar(wot[i]?'W':'S');
				return 0;
			}
		}
	}
	printf ("-1\n");
    return 0;
}


#include<bits/stdc++.h>
#define For(i,x,y) for (register int i=(x);i<=(y);i++)
#define FOR(i,x,y) for (register int i=(x);i<(y);i++)
#define Dow(i,x,y) for (register int i=(x);i>=(y);i--)
#define Debug(v) for (auto i:v) printf("%lld ",i);puts("")
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ep emplace_back
#define siz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define fil(a,b) memset((a),(b),sizeof(a))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pa;
typedef pair<ll,ll> PA;
typedef vector<int> poly;
inline ll read(){
    ll x=0,f=1;char c=getchar();
    while ((c<'0'||c>'9')&&(c!='-')) c=getchar();
    if (c=='-') f=-1,c=getchar();
    while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
    return x*f;
}

int main(){
	int n=read(),m=read(),k=read();
	printf("%d\n",k/max(n,m)+(k%max(n,m)>0));
}

#include <bits/stdc++.h>
using namespace std;

int main() {
  double H, W, N;
  cin >> H >> W >> N;

  if(H >= W) cout << ceil(N/H) << endl;
  else cout << ceil(N/W) << endl;
}


#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <cstring>

using namespace std;

#define FOR(i,a,b) for (ll i = (a); i < (b); i++)
#define REP(i,n) FOR(i,0,n)

typedef long long ll;

int c[10];

int main(){
	int n;

	while (cin >> n, n){
		REP(i,10) c[i] = 0;

		REP(i,n){
			int a;

			scanf("%d", &a);

			c[a]++;
		}

		REP(i,10){
			if (c[i] == 0) printf("-\n");
			else {
				REP(j,c[i]) printf("*");
				puts("");
			}
		}
	}

	return 0;
}

#include <iostream>
#include <stack>
#include <algorithm>
#include <cstdio>
#include <sstream>
#include <vector>
#include <map>
#include <cmath>

#define rep(x,to) for(int x=0;x<to;x++)
#define rep2(x,from,to) for(int x=from;x<to;x++)

using namespace std;

int main(void){

long long n, bg, tn, su;

	while(cin >> n){
		if(n==0 || cin.eof()) break;
		map<int,long long> sk;
		vector<int> jun;
		rep(i,n){
			cin >> bg >> tn >> su;
			if(sk[bg]==0) jun.push_back(bg);
			sk[bg] += tn * su;
		}
		int cnt=0;
		rep(i,jun.size()){
			if(sk[jun[i]] >= 1000000){
				cout << jun[i] << endl;
				cnt++;
			}
		}
		if(cnt==0) cout << "NA" << endl;
	}
	return 0;

}


#include"bits/stdc++.h"

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define REP(i, n) for (int i = 1; i <= (int)(n); i++)
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
using namespace std;
using ll = long long;
using pi = pair<int, int>;
const ll INF = 1LL << 60;

int main() {
	ll x, y,ans=0;
	cin >> x >> y;
	if (x * y == 0) {
		ans = abs(x) + abs(y);
		if (y < x)ans++;
	}
	else if (x * y < 0) {
		ans = abs(abs(x) - abs(y)) + 1;
	}
	else if (0 < x * y) {
		ans = abs(abs(x) - abs(y));
		if (y < x)ans += 2;
	}
	cout << ans << endl;
	return 0;
}

#include<iostream>
#include<algorithm>
#include<cstring>
#include<stdio.h>
#include<cstdio>
#include<string.h>
#include<cmath>
using namespace std;
bool prime(int n) {
	if (n == 1)return false;
	if (n == 2)return true;
	if (n == 3)return true;
	if (n == 4)return false;
	for (int i = 2; i < ceil(sqrt(n)); i++) {
		if (n % i == 0) {
			return false;
		}
	}
	return true;
}
int lst[110];
int main() {
	int n,x,rec;
	cin >> n>>x;
	long long sum=0;
	int ans = 0;
	for (int i = 0; i < n; i++) {
		cin >> lst[i];
	}
	sort(lst, lst + n);
	for (int i = 0; i < n; i++) {
		sum += lst[i];
		if (sum <= x)ans++;
		else break;
	}
	if (sum < x) {
		cout << ans - 1 << endl;
	}
	else cout << ans << endl;
	return 0;
}


#include <iostream>
using namespace std;
const int MAX = 500;

int main() {
	int n, m, Q;
	cin >> n >> m >> Q;
	int S[MAX+1][MAX+1] = {};
	for (int i = 0; i < m; i++) {
		int l, r;
		cin >> l >> r;
		S[l][r]++;
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			S[i][j] += S[i][j-1];
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			S[i][j] += S[i-1][j];
		}
	}
	auto sum_rect = [&](int x0, int y0, int x1, int y1) {
		return S[x1][y1] - S[x0-1][y1] - S[x1][y0-1] + S[x0-1][y0-1];
	};
	for (int query = 0; query < Q; query++) {
		int p, q;
		cin >> p >> q;
		int ans = sum_rect(p, p, q, q);
		cout << ans << endl;
	}
	return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <queue>
#include <string>
#include <set>
#include <bitset>
#include <unordered_map>
#include <cmath>
#include <functional>
#include <map>
#include <cstdlib>
#include <stack>

using namespace std;
using ll = long long;
using Pii = pair<int, int>;
using Pll = pair<ll, ll>;
template <class T>
using Vvec = vector<vector<T> >;
using Graph = Vvec<int>;

template <class T>
void debug(T& v)
{
    for(auto& x: v) cout << x << " ";
    cout << endl;
}

void inputGraph(Graph& graph, int num_edge, bool is_bidirectional, bool is_zero_indexed = false){
    int u, v;
    for(int i=0; i<num_edge; i++){
        cin >> u >> v;
        if(!is_zero_indexed){
            u--; v--;
        }
        graph[u].emplace_back(v);
        if(is_bidirectional) graph[v].emplace_back(u);
    }
}

bool isBipartite(Graph& graph, vector<int>& vis, int tmp, int from){
    if(vis[tmp] >= 0) return true;
    bool ret = true;
    vis[tmp] = (from == -1) ? 0 : 1 - vis[from];
    for(auto& to: graph[tmp]){
        if(to != from){
            ret &= isBipartite(graph, vis, to, tmp);
            ret &= (vis[tmp] == 1-vis[to]);
        }
    }
    return ret;
}

int main()
{
    int N, M;
    cin >> N >> M;
    Graph graph(N);
    inputGraph(graph, M, true);

    ll u = 0, v = 0, w = 0;
    vector<int> vis(N, -1);
    for(int i=0; i<N; i++){
        if(vis[i] >= 0) continue;
        if(graph[i].size()==0) w++;
        else if(isBipartite(graph, vis, i, -1)) u++;
        else v++;
    }

    cout << u*u + (u+v)*(u+v) + w*(2*N-w) << endl;
}


#include <iostream>
#include <cstring>
#include <map>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <queue>
#include <list>
#include <numeric>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <math.h>
#include <stack>
#include <climits>
#include <bitset>
#include <utility>

using namespace std;
typedef long long ll;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

//最大公約数
ll gcd(ll x, ll y) {
    ll tmp = 0;
    if (x < y){
        tmp=x;
        x=y;
        y=tmp;
    }
    while (y > 0) {
        ll r = x % y;
        x = y;
        y = r;
        }
    return x;
}

//最大公倍数
ll lcm(ll x,ll y){
    return x/gcd(x,y)*y;
}

const int MAX = 1e6+1;
const ll MOD = 1e9+7;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

//階乗
ll kaijo(ll k){
    ll sum = 1;
    for (ll i = 1; i <= k; ++i)
    {
        sum *= i;
        sum%=1000000000+7;
    }
    return sum;
}

long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

//sieve(MAX);でベクトルIsPrimeに「MAXまでの数値の素数の真偽」を格納する。
vector<bool> IsPrime;
void sieve(size_t max){
    if(max+1 > IsPrime.size()){     // resizeで要素数が減らないように
        IsPrime.resize(max+1,true); // IsPrimeに必要な要素数を確保
    }
    IsPrime[0] = false; // 0は素数ではない
    IsPrime[1] = false; // 1は素数ではない

    for(size_t i=2; i*i<=max; ++i) // 0からsqrt(max)まで調べる
        if(IsPrime[i]) // iが素数ならば
            for(size_t j=2; i*j<=max; ++j) // (max以下の)iの倍数は
                IsPrime[i*j] = false;      // 素数ではない
}

struct UnionFind {
    vector<int> par;
    UnionFind(int n) : par(n, -1) { }
    int root(int x) {
        if (par[x] < 0) return x;
        else return par[x] = root(par[x]);
    }
    bool issame(int x, int y) {
        return root(x) == root(y);
    }
    bool merge(int x, int y) {
        x = root(x); y = root(y);
        if (x == y) return false;
        if (par[x] > par[y]) swap(x, y); // merge technique
        par[x] += par[y];
        par[y] = x;
        return true;
    }
    int size(int x) {
        return -par[root(x)];
    }
};

ll count(int n, int a){
    ll bunshi = 1;
    for(int i = 0; i < a; i++){
        bunshi*=(n-i);
        bunshi%=MOD;
    }
    ll bunbo = 1;
    for(int i = 1; i < a+1; i++){
        bunbo*=i;
        bunbo%=MOD;
    }
    bunbo = modpow(bunbo,MOD-2,MOD);
    // cout<<(bunshi*bunbo)%MOD<<endl;
    return (bunshi*bunbo)%MOD;
}

// 約数列挙。約数をvector<ll>で返す。計算量はsqrt(n)。
vector<ll> divisor(ll n) {
    vector<ll> ret;
    for(ll i = 1; i * i <= n; i++) {
        if(n % i == 0) {
        ret.push_back(i);
        if(i * i != n) ret.push_back(n / i);
        }
    }
    sort(begin(ret), end(ret));
    return (ret);
}

// ここから開始
int main(){
    int x,y;
    cin>>x>>y;
    int a[3] = {300000,200000,100000};
    ll ans = 0;
    if(0<x&&x<4){
        ans+=a[x-1];
    }
    if(0<y&&y<4){
        ans+=a[y-1];
    }
    if(x==1&&y==1){
        ans+=400000;
    }
    cout<<ans<<endl;
    return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;

#define iter(i, n) for (int i = 1; i <= n; ++i)
#define iter_r(i, n) for (int i = n; i >= 1; --i)

const int mod = 998244353;

#define NR 1010000
const int N = 1e6 + 10;
int n, m;

struct Int {
	int v;

	Int(int v = 0) : v(v) {}

	void operator+=(Int b) { v = (v + b.v) % mod; }
	void operator-=(Int b) { v = (v - b.v + mod) % mod; }
	void operator*=(Int b) { v = 1ll * v * b.v % mod; }
};

Int fac[NR], inv[NR];

Int operator+(Int a, Int b) { return (a.v + b.v) % mod; }
Int operator-(Int a, Int b) { return (a.v - b.v + mod) % mod; }
Int operator*(Int a, Int b) { return 1ll * a.v * b.v % mod; }

Int F(int n, int m) {
	return fac[n + m] * inv[n] * inv[m];
}

Int pr(Int a, int z) {
	Int s = 1;
	while (z > 0) {
		if (z % 2 == 1) s *= a;
		a *= a;
		z /= 2;
	}
	return s;
}

Int get_inv(Int a) { return pr(a, mod - 2); }

int main() {
	fac[0] = inv[0] = 1;
	iter(i, N) fac[i] = fac[i - 1] * i;
	inv[N] = get_inv(fac[N]);
	iter_r(i, N - 1) inv[i] = inv[i + 1] * (i + 1);

	scanf("%d%d", &n, &m); ++n; ++m;
	if (n > m) swap(n, m);
	Int last = 0, speed = 0, ans = 0;
	int _x = -1;
	const Int tot = F(n - 1, m - 1), tmp0 = F(n - 1, m - 2);
	iter(q, n + m - 2) {
	//	if (q > n - 1 && _x < n - 1) last -= n - 1;
	//	if (q > m - 1) last -= m - 1;
		if (_x < n - 1) {
			if (q % 2 == 1) {
				++_x;
				int y = q - _x;

				if (_x == 0) {
					speed += F(n - 2, m - 1);
					speed += F(n - 1, m - 2);
				} else {
					//printf("!!\n");
					speed += F(_x, y - 2) * F(n - _x - 1, m - y - 1);
					speed += F(y - 2, _x) * F(m - _x - 1, n - y - 1);
				}
			} else {

				int y = q - _x;
			//	printf("c[%d %d]\n", _x, y);
				speed -= F(_x, y - 2) * F(n - _x - 2, m - y);
				speed -= F(y - 2, _x) * F(m - _x - 2, n - y);
			}
		} else speed = tmp0;
		last += speed;
	//	printf("c%d %d (%d %d %d %d)\n" ,last.v, speed.v, q, n, m, _x);

//		printf("[%d %d]\n", _x, q-_x);
//		printf("!%d %d\n", last.v, tot.v);
		ans += last * get_inv(q);
	}
	printf("%d\n", (ans * get_inv(tot)).v);
	return 0;
}

#include <cstdio>
#include <algorithm>
using namespace std;
const int mod = 998244353;
typedef long long LL;
const int MAXN = 1e6 + 6;
LL n , m , fac[MAXN] , inv[MAXN] , finv[MAXN];
int main() {
	scanf("%lld %lld" , &n , &m);
	fac[0] = 1;
	for (LL i = 1; i <= n + m; ++i) fac[i] = fac[i - 1] * i % mod;
	finv[1] = inv[1] = 1;
	finv[0] = 1;
	for (LL i = 2; i <= n + m; ++i) inv[i] = (mod - mod / i) * inv[mod % i] % mod , finv[i] = finv[i - 1] * inv[i] % mod;
	LL ans = 0;
	for (int k = 1; k <= min(n , m); ++k) {
		ans = (ans + inv[2] * fac[n - k + m - k] % mod * finv[m - k] % mod * finv[n - k] % mod * fac[2 * k] % mod * finv[k] % mod * finv[k] % mod * finv[n + m] % mod * fac[n] % mod * fac[m] % mod) % mod;
	}
	ans = (ans + max(n , m)) % mod;
	printf("%lld" , ans);
	return 0;
}


#pragma region header
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <math.h>
using namespace std;
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define rev(i, n) for(int i = (int)(n - 1); i >= 0; i--)
#define rev1(i, n) for(int i = (int)(n); i > 0; i--)
#define pb push_back
#define ts to_string
#define all(v) (v).begin(), (v).end()
#define resort(v) sort((v).rbegin(), (v).rend())
#define vi vector<int>
#define vvi vector<vector<int>>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
#define vs vector <string>
#define vvs vector <vector<string>>
using ll = long long;
using P = pair<int, int>;
/* ----------------よく使う数字や配列----------------- */
int dx[] = { 1,0,-1,0 };
int dy[] = { 0,1,0,-1 };
constexpr ll mod = 1e9 + 7;
constexpr ll inf = INT32_MAX / 2;
constexpr ll INF = LLONG_MAX / 2;
constexpr long double eps = DBL_EPSILON;
constexpr long double pi = 3.141592653589793238462643383279;
/* ----------------------end----------------------- */

/* --------------------テンプレート------------------ */
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
/* ----------------------end----------------------- */

/* --------------------ライブラリ-------------------- */
ll fact(int i) {       //階乗
    if (i == 0) return 1;
    return (fact(i - 1)) * i % mod;
}
ll gcd(ll a, ll b) {        //最大公約数
    if (b == 0) return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b) {      //最小公倍数
    return a * b / gcd(a, b);
}
int keta(ll n) {        //桁数を求める
    if (n == 0) return 1;
    int count = 0;
    while (n != 0) {
        n /= 10;
        count++;
    }
    return count;
}
bool isprime(ll a)//素数判定、primeならtrue,違うならfalse
{
    if (a < 2) return false;
    else if (a == 2) return true;
    else if (a % 2 == 0) return false;
    double m = sqrt(a);
    for (int i = 3; i <= m; i += 2)
    {
        if (a % i == 0)
        {
            return false;
        }
    }

    // 素数である
    return true;
}
ll ketasum(ll n) {    //各桁の和
    ll sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
/* ----------------------end----------------------- */
#pragma endregion
signed main() {
    int X;
    cin >> X;
    cout << X / 500 * 1000 + X % 500 / 5 * 5 << endl;
}

#include <iostream> // cout, endl, cin
#include <cmath> //sqrt pow
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower

#define rep(i,n) for(int i = 0; i < n; i++)
#define vi vector<int>
#define vvi vector<vi>
#define pii pair<int, int>
#define mod 1000000007
using ll = long long;
using namespace std;
int main(){
  int r;
  cin >> r;
  if(r >= 2800){
    cout << "AGC" << endl;
  }else if(r >= 1200){
    cout << "ARC" << endl;
  }else{
    cout << "ABC" << endl;
  }
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define repr(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define FORR(i, m, n) for (int i = (m); i >= (n); --i)
#define equals(a, b) (fabs((a) - (b)) < EPS)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const ll mod = 1000000007;
//const ll mod = 998244353;
const int inf = 1e9 + 10;
const ld INF = 1e18;
const ld EPS = 1e-10;
const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout << fixed << setprecision(25);

  int n;
  cin >> n;
  vector<ld> a(n);
  rep(i, n) cin >> a[i];

  ld ave = 0;
  rep(i, n) ave += a[i];
  ave /= n;
  int ans = -1;
  ld res = INF;
  rep(i, n) if (chmin(res, fabs(a[i] - ave))) ans = i;
  cout << ans << '\n';

  return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define rep( i, n, m ) for(int i = ( n ); i < ( m ); i++)
int main(void){
	int N;
  	cin >> N;
  	vector<pair<float, int>> vec(N);
  	float avg = 0.0f;
  	rep(i,0,N){
      	int input;
      	cin >> input;
      	vec[i] = make_pair(input, i);
      	avg+=(float)vec[i].first;
    }
  	avg/=N;
  	float minimum  = vec[0].first;
  	rep(i,0,N){
      	vec[i].first = abs(vec[i].first- avg);
      	if (minimum > vec[i].first)
          	minimum = vec[i].first;
    }
  	rep(i,0,N){
      	if ( minimum == vec[i].first){
    		cout << i << endl;
          	return 0;
      	}
    }
}


#include<bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target ("sse4")
using namespace std;
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define MEM(x,a) memset((x),a,sizeof((x)))
#define F first
#define S second
#define imx INT_MAX
const long long MOD = (long long)(1e9+7);
const long long MMX = (long long)(1e18);
typedef long long LL;
typedef pair<int,int> pii;
int n,x,ans;
LL pow2[50];
map<int,int>mp;
priority_queue<int>pq;
int main()
{
    pow2[0]=1;
    for(int i=1;i<=31;i++)pow2[i]=pow2[i-1]*2;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        mp[x]++;
        pq.push(x);
    }
    while(!pq.empty())
    {
        if(mp[pq.top()]==0)
        {
            pq.pop();
            continue;
        }
        mp[pq.top()]--;
        for(int i=31;i>-1;i--)
        {
            if(pow2[i]-pq.top()>pq.top())continue;
            if(mp[pow2[i]-pq.top()]>0)
            {
                mp[pow2[i]-pq.top()]--;
                ans++;
                break;
            }
        }
        pq.pop();
    }
    printf("%d",ans);
}

#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<(n);i++)
#define ALL(c) (c).begin(),(c).end()

const int MN = 100010;

int N;
int a[3][MN];
pii b[MN];
ll flip[2], inv[2];

template<class T>
class BIT {
	T bit[MN];
	int n;

public:
	BIT() {
		n = N + 10;
		memset(bit, 0, sizeof(bit));
	}

	T sum(int i) {
		++i;
		T s = 0;
		while (i > 0) {
			s += bit[i];
			i -= i & -i;
		}
		return s;
	}

	void add(int i, T x) {
		++i;
		while (i < n) {
			bit[i] += x;
			i += i & -i;
		}
	}
};

int main() {
	cin >> N;

	rep(i, 3) {
		rep(j, N) {
			cin >> a[i][j];
			--a[i][j];
		}
	}

	rep(i, N) {
		if (a[1][i] == a[0][i] + 1 && a[2][i] == a[0][i] + 2) {
			b[i] = mp(a[0][i] / 3, 0);
		} else if (a[1][i] == a[0][i] - 1 && a[2][i] == a[0][i] - 2) {
			b[i] = mp(a[0][i] / 3, 1);
		} else {
			puts("No");
			return 0;
		}
		if (i % 4 >= 2) {
			b[i].se ^= 1;
		}
		if (b[i].fi % 2 != i % 2) {
			puts("No");
			return 0;
		}
	}

	BIT<int> T[2];

	rep(i, 2) { //parity
		for (int j = i; j < N; j += 2) {
			flip[i] += (b[j].se != (b[j].fi % 4 >= 2));
			inv[i] += T[i].sum(N) - T[i].sum(b[j].fi);
			T[i].add(b[j].fi, 1);
		}
	}

	puts(inv[0] % 2 == flip[1] % 2 && inv[1] % 2 == flip[0] % 2 ? "Yes" : "No");

	return 0;
}


#include<iostream>
#include<string.h>
#include<string>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<vector>
#include<cmath>
#include<utility>
#include<set>
#define ll long long int
#define ld long double
#define INF 1000000000
#define EPS 0.0000000001
#define rep(i,n) for(i=0;i<n;i++)
using namespace std;
typedef pair<int, int> pii;

int main()
{
  int h,w;
  int i,j;
  while(1){
    cin>>h>>w;
    if(h==0 && w==0)break;
    int len=h*h+w*w;
    int ans=0;
    for(i=h+1;i*i<len/2;i++){//i:tate
      double left=len-i*i;
      // printf("i*i=%d,left=%f,yoko=%f\n",i*i,left,sqrt(left));
      if(sqrt(left)-(int)sqrt(left)<EPS){
	ans=i;
	break;
      }
    }
    if(ans>0){
      cout<<ans<<" "<<sqrt(len-ans*ans)<<endl;
      goto END;
    }
    while(1){
      len++;
      for(i=1;i*i<len/2;i++){
	double left=len-i*i;
	//	printf("len=%d,i*i=%d,left=%f,yoko=%f\n",len,i*i,left,sqrt(left));
	left=sqrt(left);
	if(left-(int)left<EPS){
	  cout<<i<<" "<<left<<endl;
	  goto END;
	}
      }

    }
  END:;

  }
}

#include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "iomanip"
#include "random"

using namespace std;

const long long int MOD = 1000000007;
const long double EPS = 0.00000001;
const long double PI = 3.1415926535897932384626433;

long long int N, M, K, H, W, L, R;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);

	vector<pair<int, pair<int,int>>>v;
	for (int i = 1; i <= 150; i++) {
		for (int j = i + 1; j <= 150; j++) {
			v.push_back({ i*i + j*j ,{i,j} });
		}
	}
	sort(v.begin(), v.end());
	cin >> H >> W;
	while (H) {
		bool flag = false;
		for (auto i : v) {
			if (flag) {
				cout << i.second.first << " " << i.second.second << endl;
				break;
			}
			if (i.second.first == H&&i.second.second == W) {
				flag = true;
			}
		}
		cin >> H >> W;
	}
	return 0;
}


#include "bits/stdc++.h"
#define ll long long
#define rep2(i,a,b) for(int i=(a);i<=(b);++i)
#define rep(i,n) for(int i=0;i<n;i++)
#define pii pair<int,int>
#define ti3 tuple<int,int,int>
#define pq priority_queue<int>
#define pqg priority_queue<int,vector<int>,greater<int>>
ll int MOD=998244353;
#define N 3000000

using namespace std;
string alphabet("abcdefghijklmnopqrstuvwxyz");

main(){
    ll int k;
    cin>>k;
    ll int kk=k;
    int n=50;
    ll int a[50]={};
    rep(i,50){
        a[i]=kk/50;
        k-=kk/50;
    }
    rep(i,50){
        if(k>0){
            a[i]++;
            k--;
        }
    }
    cout<<50<<endl;
    rep(i,50){
        a[i]=(ll)51*a[i]-kk+(ll)49;
        cout<<a[i]<<" ";
    }
    return 0;
}

#include <bits/stdc++.h>
typedef long long ll;
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,a) FOR(i,0,a)

using namespace std;

int main(){
	ll K;
	cin>>K;
	cout<<50<<endl;
	REP(i,50){
		ll ans;
		if (i<K%50){
			ans=100-(K%50)+K/50;
		}else{
			ans=49-(K%50)+K/50;
		}
		if (i){
			cout<<" ";
		}
		cout<<ans;
	}
	cout<<endl;
	return 0;
}


#include <iostream>
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <set>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>

using namespace std;

#define f first
#define s second

typedef long long LLI;

int n;

pair<int, pair<int, int> > p[5001];
long long dp[5001][5001];

const long long inf = 1e15;

int main() {
	scanf("%d", &n);
	for(int i = 0; i < n; ++i) {
		scanf("%d %d", &p[i].s.f, &p[i].s.s);
		p[i].f = p[i].s.f + p[i].s.s;
	}
	sort(p, p + n);

	for(int i = 0; i < 5001; ++i) {
		dp[i][0] = 0;
		for(int j = 1; j < 5001; ++j) dp[i][j] = inf;
	}

	int ans = 1;

	dp[0][1] = p[0].s.s;

	for(int i = 1; i < n; ++i) {
		for(int j = 1; j <= n; ++j) {
			dp[i][j] = dp[i-1][j];
			if(p[i].s.s + dp[i-1][j-1] < dp[i][j] && p[i].s.f >= dp[i-1][j-1]) dp[i][j] = p[i].s.s + dp[i-1][j-1];
			if(dp[i][j] < inf) ans = max(ans, j);
		}
	}
	printf("%d\n", ans);
	return 0;
}

#include <bits/stdc++.h>
using namespace std ;

const int N = 5010 ;
const long long inf = 10000000000000000 ;
pair<int,int> zab [ N ] ;

bool cmp ( pair<int,int> A, pair<int,int> B ) {
    return A.first + A.second < B.first + B.second ;
}

long long dp [ N ][ 3 ];

int main() {
 //   freopen("input.txt", "r", stdin) ;
    int n ; cin >> n ;
    for ( int i = 0 ; i < n ; ++i )
        cin >> zab[i].first >> zab[i].second ;
    sort ( zab, zab+n, cmp ) ;
    int ans =0 ;
    for ( int i = 1 ; i <= n ; ++i ) {
        for ( int j = 0 ; j < n ; ++j ) {
            if ( i == 1 ) dp[j][i%2] = zab[j].first ;
            else if ( j + i <= n ) dp[j][i%2] = min ( 1ll*zab[j].first, dp[j+1][(i-1)%2] - zab[j].second );
            else dp[j][i%2] = -inf ;
        }
        bool kPosible = (dp[n-1][i%2] >= 0ll) ;
        for ( int j = n-2 ; j >= 0 ; --j ) {
            dp[j][i%2] = max ( dp[j][i%2], dp[j+1][i%2] ) ;
            kPosible |= (dp[j][i%2]>=0ll) ;
        }
        if ( kPosible ) ans = i ;
    }
    cout << ans << '\n' ;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define rep(i,x) for(int i=0;i<x;i++)
#define put(ans)    cout << ans << endl;

int main(){
    string t("2018"),s;

    rep(i,10){
        char c; cin >> c;
        if(i>=0 && i<=3){
            cout << t[i];
        }else{
            cout << c;
        }
    }

    cout << endl;

    return 0;
}

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string s;
	cin >> s;

	cout << s.replace(3, 1, "8") << endl;
}


#include <bits/stdc++.h>
#define rep(i,n) for (ll i=0; i<(n); i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

int main(){
  ll h,w;
  cin >> h >> w;
  string s[h];
  vector<vector<char>> t(h, vector<char>(w));
  rep(i,h) cin >> s[i];
  rep(i,h)rep(j,w) t[i][j]='.';

  rep(i,h)rep(j,w){
    if(s[i][j]=='.') continue;
    rep(k,4){
      int ii = i+dx[k];
      int jj = j+dy[k];
      if(ii<0 || ii>h-1) continue;
      if(jj<0 || jj>w-1) continue;
      if(s[ii][jj]=='#'){
        t[ii][jj]='#';
        t[i][j]='#';
        break;
      }
    }
  }
  int cnt=0;
  rep(i,h)rep(j,w){
    if(s[i][j]==t[i][j]) cnt++;
  }
  if(cnt==h*w) cout << "Yes" << endl;
  else cout << "No" << endl;
}

#include <bits/stdc++.h>
using namespace std;

using str = string;
using ss = stringstream;

str a[60];

#define fi first
#define se second

#define DIRMAX 4
pair<int,int> dir[4]=
{
    { 0,-1},
    {-1, 0},
    { 1, 0},
    { 0, 1},
};

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(0);

    int h,w;cin>>h>>w;

    ss maketop;
    for(int i=0;i<w+2;i++)maketop<<".";

    a[0]=maketop.str();
    a[h+1]=maketop.str();

    for(int i=0;i<h;i++)
    {
        str s;
        cin>>s;
        ss makemid;

        makemid<<"."<<s<<".";

        a[i+1]=makemid.str();
    }

    bool ans=true;

    for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)
    {
        if(a[i][j]=='#')
        {
            bool c=true;
            for(int k=0;k<DIRMAX;k++)
            if(a[i+dir[k].fi][j+dir[k].se]=='#')
            {
                c=false;
                break;
            }

            if(c)
            {
                ans=false;
                break;
            }
        }
    }

    puts(ans?"Yes":"No");

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(k,i,n) for(ll i=k;i<n;++i)
int main(void){
    // Your code here!
    ll n,k;
    cin>>n>>k;
    char d[k];
    rep(0,i,k)cin>>d[i];
    rep(n,N,100001){
        string nN=to_string(N);
        bool t=true;
        rep(0,i,nN.length()){
            rep(0,j,k){
                if(d[j]==nN[i])t=false;
            }
        }
        //cout<<nN<<" "<<t<<endl;
        if(t==true){
            cout<<nN;
            return 0;
        }
    }
}

//
//AtCoder Beginner Contest 042
//C
//

#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <queue>
#include <map>
#include <set>
#include <tuple>
#include <functional>
#include <cassert>
#include <bitset>

using namespace std;

#define REP(i,n) for(ll i=0;i<(ll)(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=a;i<=(ll)(b);i++)
#define FORD(i,a,b) for(ll i=a;i>=(ll)(b);i--)
#define ALL(x) (x).begin(),(x).end()
#define RALL(x) (x).rbegin(),(x).rend()
#define SIZE(x) (int)(x).size()
#define SIZEL(x) (ll)(x).size()
#define MSG(a) cout << #a << " " << a << endl;

using ll = long long;
using ld = long double;
using Graph = vector<vector<int>>;

const double PI = 3.14159265358979323846;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

ll gcd(ll x, ll y) { return (x % y)? gcd(y, x % y): y; }    //最大公約数
ll lcm(ll x, ll y) { return x / gcd(x, y) * y; }            //最小公倍数

int main()
{
    int n, k;
    cin >> n >> k;

    vector<int> dislike(10, 0);
    REP(i, k) {
        int d;
        cin >> d;
        dislike[d]=1;
    }

    int likeMin = -1;
    REP(i, 10) {
        if (dislike[i]==0){
            likeMin = i;
            break;
        }
    }
    vector<int> ans(10010, -1);

    int over = -1;
    int nn = n;
    int pos = 0;
    while(nn>0){
        ans[pos]=nn%10;
        if (dislike[nn%10] == 1) over = pos;
        nn /= 10;
        pos++;
    }

    if (over == -1) {
        cout << n << endl;
        return 0;
    }

    REP(i, over) ans[i]=likeMin;
    FOR(i, over, pos){
        int like = -1;
        FOR(j, ans[i], 9){
            if (dislike[j]==0){
                like = j;
                break;
            }
        }
        if (like == -1){
            ans[i]=likeMin;
            if (ans[i+1]==-1) ans[i+1] = 1;
            else ans[i+1]++;
        }else{
            ans[i]=like;
            break;
        }
    }

    string sans = "";
    REP(i, ans.size()){
        if (ans[i]==-1) break;
        else sans = to_string(ans[i]) + sans;
    }
    cout << sans << endl;
    return 0;
}


#include <iostream>
#include <cstdio>
using namespace std;
int N, M;
int MOD;
int Fact[6005], Inv[6005], Pw2[6005], Pw3[6005], IPw2[6005], IPw3[6005];
int power(int n, int p){
    int sol = 1;
    while(p){
        if(p & 1)
            sol = (1LL * sol * n) % MOD;
        p /= 2;
        n = (1LL * n * n) % MOD;
    }
    return sol;
}
void precalcFact(){
    Fact[0] = 1;
    for(int i = 1; i <= N * 3; i++){
        Fact[i] = (1LL * Fact[i - 1] * i) % MOD;
    }
    Inv[N * 3] = power(Fact[N * 3], M - 2);
    for(int i = N * 3 - 1; i >= 0; i--)
        Inv[i] = (1LL * Inv[i + 1] * (i + 1)) % MOD;
}

void precalcPower(){
    Pw2[0] = 1;
    Pw3[0] = 1;
    IPw2[0] = 1;
    IPw3[0] = 1;
    for(int i = 1; i <= N * 3; i++){
        Pw2[i] = (1LL * Pw2[i - 1] * 2) % MOD;
        Pw3[i] = (1LL * Pw3[i - 1] * 3) % MOD;
        IPw2[i] = power(Pw2[i], M - 2);
        IPw3[i] = power(Pw3[i], M - 2);
    }
}
int compute(int p1, int p2, int p3){
    int ans = Fact[3 * N];
    ans = (1LL * ans * Inv[p1]) % MOD;
    ans = (1LL * ans * Inv[p2]) % MOD;
    ans = (1LL * ans * Inv[p3]) % MOD;
    ans = (1LL * ans * IPw2[p2]) % MOD;
    ans = (1LL * ans * IPw3[p3]) % MOD;
    return ans;
}
void Solve(){
    int ans = 0;
    for(int i = 0; i <= N * 3; i++){
        for(int j = 0; j <= N * 3; j++){
            int g1 = 3 * N - 2 * i - 3 * j;
            if(g1 < i)
                break;
            ans += compute(g1, i, j);
            if(ans >= MOD)
                ans -= MOD;
        }
    }
    cout << ans << '\n';
}
int main()
{
    cin >> N >> M;
    MOD = M;
    precalcFact();
    precalcPower();
    Solve();
    return 0;
}

#include <bits/stdc++.h>
// #include <atcoder/all>
// using namespace atcoder;
#define rep(i, n) for (ll i = 0; i < (ll)(n); ++i)
#define rep2(i, s, n) for (ll i = s; i < (ll)(n); i++)
#define repr(i, n) for (ll i = n; i >= 0; i--)
#define pb push_back
#define COUT(x) cout << (x) << "\n"
#define COUTF(x) cout << setprecision(15) << (x) << "\n"
#define ENDL cout << "\n"
#define DF(x) x.erase(x.begin())
#define ALL(x) x.begin(), x.end()
#define SORT(x) sort(ALL(x))
#define RSORT(x) sort(x.rbegin(), x.rend())
#define REVERSE(x) reverse(ALL(x))
#define MAX(x) *max_element(ALL(x))
#define MAXI(x) max_element(ALL(x)) - x.begin()
#define SUM(x) accumulate(ALL(x), 0ll)
#define COUNT(x, y) count(ALL(x), y);
#define ANS cout << ans << "\n"
#define YES cout << "YES\n";
#define NO cout << "NO\n";
#define Yes cout << "Yes\n";
#define No cout << "No\n";
#define YN YES else NO
#define yn Yes else No
#define init() \
  cin.tie(0);  \
  ios::sync_with_stdio(false)
#define LINE cerr << "[debug] line: " << __LINE__ << "\n";
#define debug(x) cerr << "[debug] " << #x << ": " << x << "\n";
#define debugV(v)                       \
  cerr << "[debugV] " << #v << ":";     \
  rep(z, v.size()) cerr << " " << v[z]; \
  cerr << "\n";
using namespace std;
using ll = long long;
using ld = long double;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using mll = map<ll, ll>;
using qll = queue<ll>;
using P = pair<ll, ll>;
using vp = vector<P>;
using vs = vector<string>;

template <typename T>
inline istream& operator>>(istream& i, vector<T>& v) {
  rep(j, v.size()) i >> v[j];
  return i;
}

template <typename T1, typename T2>
inline istream& operator>>(istream& i, pair<T1, T2>& v) {
  return i >> v.first >> v.second;
}

constexpr ll INF = 0x3f3f3f3f3f3f3f3f;
constexpr ld PI = 3.141592653589793238462643383279;
ll get_digit(ll x) {
  return to_string(x).size();
}

ll gcd(ll x, ll y) {
  return y ? gcd(y, x % y) : x;
}

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

template <class T>
bool chmax(T& a, const T& b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}

template <class T>
bool chmin(T& a, const T& b) {
  if (b < a) {
    a = b;
    return 1;
  }
  return 0;
}

signed main() {
  init();
  ll N, M, V, P;
  cin >> N >> M >> V >> P;
  vll A(N);
  cin >> A;
  RSORT(A);

  ll left = 0, right = N;
  while (right - left > 1) {
    ll center = (left + right) / 2;
    if (center < P) {
      left = center;
      continue;
    }

    ll after = A[center] + M;

    if (after < A[P - 1]) {
      right = center;
      continue;
    }

    ll num = ((P - 1) + 1 + N - (center + 1)) * M;
    rep2(i, P - 1, center) num += after - A[i];

    if (num < M * V)
      right = center;
    else
      left = center;
  }

  COUT(left + 1);
  return 0;
}


#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string>
#include<vector>
#include<cctype>
using namespace std;

int main(){
vector<int>a;
int n,s=0,b=0;long sum=0;
cin>>n;int nnn;
if(n>0){
	for(int i=0;i<n;i++){cin>>nnn;a.push_back(nnn);}
		 s=a[0],b=a[0];
		for(int i=0;i<a.size();i++){
			sum+=a[i];
			b=max(b,a[i]);
			s=min(s,a[i]);
		}
	cout<<s<<" "<<b<<" "<<sum<<endl;
		}
	else{
		printf("%d %d %d\n",s,b,sum);
		}
return 0;
}

#include <iostream>
#include <utility>
#include <algorithm>
using namespace std;

int partition(int A[], int p, int last){
  int x = A[last];
  int bigger_first_ind = p - 1;
  for(int j = p; j < last; j++){
    if(A[j] <= x) swap(A[++bigger_first_ind], A[j]);
  }
  swap(A[++bigger_first_ind], A[last]);
  return bigger_first_ind;
}

int main(){
  int n;
  cin >> n;
  int* A; A = new int[n];
  for(int i = 0; i < n; i++) cin >> A[i];
  int border = partition(A, 0, n-1);

  for(int i = 0; i < n-1; i++){
    if(i == border){
      cout << "[" << A[i] << "] ";
    }else
      cout << A[i] << " ";
  }
  cout << A[n-1] << endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, srt, end) for (long long i = (srt); i < (long long)(end); i++)

constexpr ll mod = 1000000000 + 7;

ll dp[200][10];

void init() {
    rep(i, 0, 200) rep(j, 0, 10) dp[i][j] = 0;
}

int main(){

    init();

    // input
    ll h, w, k;
    cin >> h >> w >> k;

    // dp
    dp[0][0] = 1;
    rep(i, 0, h) {
        rep(j, 0, w) {
            for(int bit = 0; bit < (1<<(w-1)); bit++) {
                bool f = true;
                rep(k, 0, w-2) {
                    if((bit & (1<<k)) && (bit & (1<<(k+1)))) f = false;
                }
                if(!f) continue;
                if(j >= 1 && (bit & (1 << (j-1) ) ) ) {
                    dp[i+1][j-1] += dp[i][j];
                    dp[i+1][j-1] %= mod;
                }else if(j <= w-2 && (bit & (1<<j) ) ) {
                    dp[i+1][j+1] += dp[i][j];
                    dp[i+1][j+1] %= mod;
                }else{
                    dp[i+1][j] += dp[i][j];
                    dp[i+1][j] %= mod;
                }
            }
        }
    }

    cout << dp[h][k-1] << endl;
    return 0;
}

#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cassert>
#include <cstring>
#include <string>
#include <vector>
#include <random>
#include <bitset>
#include <queue>
#include <cmath>
#include <unordered_map>
#include <set>
#include <map>
#define INCANT cin.tie(0), cout.tie(0), ios::sync_with_stdio(0), cout << fixed << setprecision(20);
#define rep(i,n) for (int i=0; i<n;++i)
#define ALL(a)  (a).begin(),(a).end()
#define PI 3.14159265358979
typedef long long ll;
using namespace std;
const ll MOD = 1e9+7LL;
const int INF = 2e9;
int H, W, K;
ll DP[101][10]; // 残りn本の段階でiにいる場合の数
ll Memo[9]; // 本数がidxのときに何通りあるか

void calc() {
  rep(i, H+1) {
    if (i==0) continue;
    rep(j, W) {
      DP[i][j] += DP[i-1][j]*Memo[j]*Memo[W-j-1]; // 左右に棒を置かない
      if (j>0) DP[i][j] += DP[i-1][j-1]*Memo[W-j-1]*Memo[j-1]; // 左に棒を置く
      if (j<W-1) DP[i][j] += DP[i-1][j+1]*Memo[W-j-2]*Memo[j]; // 右に棒を置く
      DP[i][j]%=MOD;
    }
  }
}

int main() {
  INCANT;
  cin >> H >> W >> K;
  if (W==1) {
    cout << 1 << endl;
    return 0;
  }
  Memo[0] = 1;
  Memo[1] = 1;
  rep(i, W) Memo[i+2] = Memo[i]+Memo[i+1];
  DP[0][0] = 1ll;
  calc();
  cout << DP[H][K-1] << "\n";
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ll long long
#define vll vector<ll>
#define ld long double
#define pll pair<ll,ll>
#define PB push_back
#define MP make_pair
#define F first
#define S second
#define oset tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
#define osetll tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define ook order_of_key
#define fbo find_by_order
const int MOD=1000000007;
long long int inverse(long long int i){
    if(i==1) return 1;
    return (MOD - ((MOD/i)*inverse(MOD%i))%MOD+MOD)%MOD;
}
ll POW(ll a,ll b)
{
    if(b==0) return 1;
    if(b==1) return a%MOD;
    ll temp=POW(a,b/2);
    if(b%2==0) return (temp*temp)%MOD;
    else return (((temp*temp)%MOD)*a)%MOD;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    ll n;
    cin>>n;
    string s[n];
    ll a[n],b[n];
    vector<pair<ll,ll> > v1,v2;
    for(int i=0;i<n;i++)
    {
        cin>>s[i];
        ll mx=0,temp=0;
        for(int j=0;j<s[i].size();j++)
        {
            if(s[i][j]==')') temp++;
            else temp--;
            mx=max(temp,mx);
        }
        a[i]=mx;
        temp=0;
        ll mn=0;
        for(int j=s[i].size()-1;j>=0;j--)
        {
            if(s[i][j]=='(') temp++;
            else temp--;
            mn=max(mn,temp);
        }
        b[i]=mn;
        //cout<<a[i]<<" "<<b[i]<<" ";
        if( (b[i]-a[i]) >0) v1.PB(MP(a[i],i));
        else v2.PB(MP(-b[i],i));
    }
    sort(v1.begin(),v1.end());
    sort(v2.begin(),v2.end());
    stack<ll> st;
    ll flag=0;
    for(int i=0;i<v1.size();i++)
    {
        string k=s[v1[i].S];
        for(int j=0;j<k.size();j++)
        {
            if(k[j]=='(') st.push(1);
            else
            {
                if(st.empty()) {flag=1; break;}
                else st.pop();
            }
        }
        if(flag==1) break;
    }
    if(flag==0)
    {
        for(int i=0;i<v2.size();i++)
        {
            string k=s[v2[i].S];
            for(int j=0;j<k.size();j++)
            {
                if(k[j]=='(') st.push(1);
                else
                {
                    if(st.empty()) {flag=1; break;}
                    else st.pop();
                }
            }
            if(flag==1) break;
        }
    }
    if(flag==0 && st.empty()) cout<<"Yes";
    else cout<<"No";
}

#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define Rep(i,s,n) for(int i=s;i<n;i++)
#define fi first
#define se second
#define all(c) c.begin(),c.end()
typedef long long int ll;
typedef pair<ll, ll> P;
typedef long double ld;
void Ans(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}

const ll INF=1001001001;
const ll mod=1000000007;

int main(){
  ll n;
  cin>>n;
  string s;
  P a[n];
  vector<P> b,c;
  ll s1,s2;

  rep(i,n){
    s1=0;
    s2=0;
    cin>>s;
    rep(j,s.size()){
      if(s[j]=='('){
        s1++;
      }
      else if(s[j]==')'&&s1==0){
        s2++;
      }
      else{
        s1--;
      }
    }
    a[i]=P(s1,s2);
    if(s1-s2>=0) b.push_back(P(s2,s1));
    else c.push_back(P(s1,s2));
  }

  sort(all(b));
  sort(all(c));

  s1=0;
  s2=0;
  int ch=0;

  rep(i,b.size()){
    s2+=b[i].fi;

    if(s1<s2) ch++;
    s1+=b[i].se;

    if(s1<s2) ch++;
  }

  rep(i,c.size()){
    int j=c.size()-i-1;
    s2+=c[j].se;

    if(s1<s2) ch++;
    s1+=c[j].fi;

    if(s1<s2) ch++;
  }

  Ans(ch==0&&s1==s2);

}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
using namespace __gnu_pbds;
using namespace std;
#define getbit(n, i) (((n) & (1LL << (i))) != 0)
#define setbit0(n, i) ((n) & (~(1LL << (i))))
#define setbit1(n, i) ((n) | (1LL << (i)))
#define togglebit(n, i) ((n) ^ (1LL << (i)))
char gap = 32;
template < typename T >
ostream& operator<<(ostream &os, const vector < T > &v) {
  os << '{';
  for (const auto &x: v) os << gap << x;
  return os << '}';
}
template < typename A, typename B >
ostream& operator<<(ostream &os, const pair < A, B > &p) {
  return os << '(' << p.first << gap << p.second << ')';
}

template < class T >
void read(T &x) {
  char c;
  for (c = getchar(); c < '0' || c > '9'; c = getchar());
  for (x = 0; c <= '9' && c >= '0'; c = getchar()) x = x * 10 + (c & 15);
}
#define ll long long
#define lll __int128_t
#define pb push_back
#define mp make_pair
typedef pair < int, int > ii;
typedef vector < ii > vii;
typedef vector < ll > vl;
typedef vector < int > vi;
typedef vector < vi > vvi;
typedef tree <
int,
null_type,
less < int >,
rb_tree_tag,
tree_order_statistics_node_update >
ordered_set;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll hashPrime = 1610612741;
ll dp[1001][1001];
ll mod=1000000007;
vector<string>Data;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  ll i,j,k,l,n,m;
  cin>>n>>m;
  vector<pair<ll,ll>>res;
  ll ini=1;
  ll fina=n;
  vector<ll>used(n+1,0);
  ll kola1=(m+1)/2;
  while(kola1--){
    used[ini]=1;used[fina]=1;
    res.pb({ini++,fina--});
  }
  m=m/2;
  ll cnt=2*m;
  while(m--){
    while(used[ini]==1) ini++;
    res.pb(make_pair(ini,ini+cnt));
    used[ini]=1;
    used[ini+cnt]=1;
    cnt-=2;
  }
  for(auto x:res) cout<<x.first<<" "<<x.second<<'\n';
}

#include <bits/stdc++.h>
#define ll long long
#define double long double
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define mod (ll)(1e9+7)
#define inf (ll)(3e18+7)
#define pi (double) acos(-1)
#define P pair<int,int>
#define PiP pair<int,pair<int,int>>
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    rep(i, m/2)cout << i+1 << " " << m-i << endl;
    rep(i, (m+1)/2)cout << i+1+m << " " << 2*m+1-i << endl;
}


#include<iostream>
using namespace std;
long long p=998244353,jc[200010],n,m,k,f[200010],ans;
long long ksm(long long a,long long b)
{
     long long x=1;
     for(;b;a=(a*a)%p,b/=2) if(b%2==1) x=(x*a)%p;
     return x;
}
long long c(long long x,long long y)
{
     long long z=jc[x];
     if(y<=0) return 1;
     z=(z*ksm(jc[y],p-2))%p;
     z=(z*ksm(jc[x-y],p-2))%p;
     return z;
}
int main()
{
    int i;
    cin>>n>>m>>k;
    jc[0]=1;
    for(i=1;i<=n;i++) jc[i]=(jc[i-1]*i)%p;
    f[1]=m;
    for(i=2;i<=n;i++) f[i]=(f[i-1]*(m-1))%p;
    for(i=0;i<=k;i++) ans=(ans+c(n-1,n-i-1)*f[n-i])%p;
    cout<<ans;
    cin>>i;
}

#include <bits/stdc++.h>
#define MOD 998244353LL
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

ll fact[400005];

ll mod_pow(ll x,ll n){
	ll res=1;
	while(n>0){
		if(n&1LL){
			res=res*x%MOD;
		}
		x=x*x%MOD;
		n>>=1LL;
	}
	return res;
}

ll extgcd(ll a,ll b,ll& x,ll& y){
	ll d=a;
	if(b!=0LL){
		d=extgcd(b,a%b,y,x);
		y-=(a/b)*x;
	}else{
		x=1;
		y=0;
	}
	return d;
}

ll mod_inverse(ll a,ll m){
	ll x,y;
	extgcd(a,m,x,y);
	return (m+x%m)%m;
}

ll mod_fact(ll n,ll p,ll& e){
	e=0;
	if(n==0)return 1;
	ll res=mod_fact(n/p,p,e);
	e+=n/p;
	if(n/p%2!=0){
		return res*(p-fact[n%p])%p;
	}
	return res*fact[n%p]%p;
}

ll mod_comb(ll n,ll k,ll p){
	if(n<0 || k<0 || n<k)return 0;
	ll e1,e2,e3;
	ll a1=mod_fact(n,p,e1),a2=mod_fact(k,p,e2),a3=mod_fact(n-k,p,e3);
	if(e1>e2+e3)return 0;
	return a1*mod_inverse(a2*a3%p,p)%p;
}

int n,m,k;

int main(void){
	fact[0]=1;
	fact[1]=1;
	for(ll i=2;i<=400000;i++){
		fact[i]=fact[i-1]*i%MOD;
	}
	scanf("%d%d%d",&n,&m,&k);
	ll ans=mod_pow(m,n);
	ll co=1;
	for(int i=k+1;i<n;i++){
		ll ch=n-i-1;
		ll val=m;
		val=val*mod_pow(m-1,ch)%MOD;
		val=val*mod_comb(n-1,ch,MOD)%MOD;
		ans-=val;
		if(ans>=MOD){
			ans-=MOD;
		}
		if(ans<0){
			ans+=MOD;
		}
	}
	printf("%lld\n",ans);
	return 0;
}


#include <iostream>
#include <iomanip>
#include<vector>
using namespace std;
int main()
{
	while(1)
	{
		int N;
		cin >> N;
		if(N == 0)
		{
			return 0;
		}

		vector<vector<int>> map;

		//??????????????????
		for(int i = 0; i < N+1; i++)
		{
			vector<int> column;
			for(int j = 0; j < N + 1; j++)
			{
				if(i == N)
				{
					column.push_back(0);
				}
				else if(j != N)
				{
					int value;
					cin >> value;
					column.push_back(value);
				}
				else
				{
					column.push_back(0);
				}

			}
			map.push_back(column);
		}
		//?????????????¨????
		int totalSum = 0;
		//????????????????¨????
		for(int i = 0; i < N; i++)
		{
			int sum = 0;
			for(int j = 0; j < N; j++)
			{
				sum += map[i][j];
			}
			map[i][N] = sum;
		}
		//????????????????¨????
		for(int i = 0; i < N; i++)
		{
			int sum = 0;
			for(int j = 0; j < N; j++)
			{
				sum += map[j][i];
			}
			map[N][i] = sum;
			totalSum += sum;
		}
		//????????????????¨???????????????£??\
		map[N][N] = totalSum;

		for(int i = 0; i < N + 1; i++)
		{
			for(int j = 0; j < N + 1; j++)
			{
				cout << setw(5) << right << map[i][j];
			}
			cout << endl;
		}
	}

}

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    const int MAX = 10001;
    bool isPrime[MAX];
    fill_n(isPrime, MAX, true);
    for (int i = 4; i < MAX; i += 2) {
        isPrime[i] = false;
    }
    for (int i = 3; i * i <= MAX; i += 2) {
        if (isPrime[i]) {
            for (int j = i * 2; j < MAX; j += i) {
                isPrime[j] = false;
            }
        }
    }
    while (true) {
        int n;
        cin >> n;
        if (n == 0) {
            break;
        }
        if (n % 2 == 0) {
            n--;
        }
        for (int i = n; i >= 5; i -= 2) {
            if (isPrime[i] && isPrime[i - 2]) {
                cout << i - 2 << " " << i << endl;
                break;
            }
        }
    }
}


#include <bits/stdc++.h>

using namespace std;

int main() {
  // freopen("in.txt", "r", stdin);
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  long long x;
  cin >> n >> x;
  vector<long long> b(n), l(n), u(n);
  long long loss = 0;
  for (int i = 0; i < n; i++) {
    cin >> b[i] >> l[i] >> u[i];
    loss += b[i] * l[i];
  }
  vector<long long> value(n);
  for (int i = 0; i < n; i++) {
    value[i] = x * u[i] - b[i] * (u[i] - l[i]);
  }
  vector<int> order(n);
  iota(order.begin(), order.end(), 0);
  sort(order.begin(), order.end(), [&](int i, int j) {
    return value[i] > value[j];
  });
  vector<long long> pref(n + 1);
  for (int i = 0; i < n; i++) {
    pref[i + 1] = pref[i] + value[order[i]];
  }
  long long ans = (long long) 9e18;
  for (int it = 0; it < n; it++) {
    int i = order[it];
    for (long long coeff : {l[i], u[i]}) {
      int low = 0, high = n;
      while (low <= high) {
        int mid = (low + high) >> 1;
        long long cur = loss;
        if (coeff == u[i]) {
          cur += b[i] * (u[i] - l[i]);
        }
        long long can_get = pref[mid];
        long long vals = mid;
        if (it < mid) {
          can_get -= value[i];
          vals -= 1;
        }
        can_get += x * coeff;
        if (can_get >= cur) {
          can_get -= x * coeff;
          long long need = 0;
          if (can_get < cur) {
            need = (cur - can_get + coeff - 1) / coeff;
          }
          ans = min(ans, vals * x + need);
        }
        if (low == high) {
          break;
        }
        if (can_get >= cur) {
          high = mid;
        } else {
          low = mid + 1;
        }
      }
    }
  }
  cout << ans << '\n';
  return 0;
}

#include <iostream>
#include <algorithm>
#include <vector>
#include <tuple>
#include <functional>
using namespace std;
using T=tuple<int64_t,int>;

int main(){
    int64_t N,X;
    cin>>N>>X;
    vector<int64_t> B(N),L(N),U(N);
    for(int i=0;i<N;i++){
        cin>>B[i]>>L[i]>>U[i];
    }
    vector<T> V;
    for(int i=0;i<N;i++){
        V.emplace_back(U[i]*(X-B[i])+L[i]*B[i],i);
    }
    sort(V.begin(), V.end(),greater<T>());
    function<bool(int64_t)> test = [&](int64_t sum){
        int64_t total=0;
        for(int i=0;i<N;i++){
            int idx;
            tie(ignore,idx)=V[i];
            if(i<(sum+X-1)/X){
                total+=U[idx]*(X-B[idx]);
            }else{
                total+=-L[idx]*B[idx];
            }
        }
        if(sum%X==0){
            return total>=0;
        }
        int64_t maximum=-10000000000000;
        for(int i=0;i<N;i++){
            int idx;
            tie(ignore,idx)=V[i];
            int64_t diff = max(U[idx]*(sum%X-B[idx]),L[idx]*(sum%X-B[idx]));
            if(i<(sum+X-1)/X){
                maximum = max(maximum, total-U[idx]*(X-B[idx])+diff);
            }else{
                int edge = get<1>(V[(sum+X-1)/X-1]);
                maximum = max(maximum, total-U[edge]*(X-B[edge])-L[edge]*B[edge]+L[idx]*B[idx]+diff);
            }
        }
        // cout<<sum<<' '<<maximum<<' '<<total<<endl;
        return maximum>=0;
    };
    int64_t lb=0,ub=X*N;
    while(ub-lb>1){
        int64_t mid=(lb+ub)/2;
        if(test(mid)){
            ub=mid;
        }else{
            lb=mid;
        }
    }
    if(lb==0&&test(lb)){
        cout<<lb<<endl;
    }else{
        cout<<ub<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N=1000005;
const int mo=998244353;
int fac[N],inv[N],n,m,ans;
int C(int x,int y){
	return 1ll*fac[x]*inv[y]%mo*inv[x-y]%mo;
}
int main(){
	fac[0]=inv[0]=inv[1]=1;
	for (int i=2;i<N;i++)
		inv[i]=1ll*(mo-mo/i)*inv[mo%i]%mo;
	for (int i=1;i<N;i++)
		fac[i]=1ll*fac[i-1]*i%mo,
		inv[i]=1ll*inv[i-1]*inv[i]%mo;
	scanf("%d%d",&n,&m);
	for (int i=1;i<=n&&i<=m;i++)
		ans=(ans+1ll*C(i*2,i)*C(n+m-i*2,n-i))%mo;
	ans=1ll*ans*inv[n+m]%mo*fac[n]%mo*fac[m]%mo*(mo+1)/2%mo;
	printf("%d",(ans+max(n,m))%mo);
}

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <iomanip>
#include <numeric>
#include <queue>
#include <cmath>
using namespace std;

int main() {
    // 10x + 5y + z = Y
    // x + y + z = N
    // 9x + 4y = Y - N
    int n, yy;
    cin >> n >> yy;
    yy /= 1000;
    int x = -1, y = -1, z = -1;
    for (int i = 0; 4 * i <= yy - n; i++) {
        int t = yy - n - 4 * i;
        if (t >= 0 && t % 9 == 0 && n - t / 9 - i >= 0) {
            x = t / 9;
            y = i;
            z = n - x - y;
            break;
        }
    }
    cout << x << " " << y << " " << z << endl;
}


#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define FOR(i,s,n) for(int i = s; i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(n) (n).begin(), (n).end()
#define RALL(n) (n).rbegin(), (n).rend()
#define ATYN(n) cout << ( (n) ? "Yes":"No") << endl;
#define CFYN(n) cout << ( (n) ? "YES":"NO") << endl;
#define OUT(n) cout << (n) << endl;
using ll = long long;
using ull = unsigned long long;
using pii = pair<int,int>;

int main(void)
{
    IOS
    const int HW = 100;
    const char W = '.';
    const char B = '#';
    int a, b;
    cin >> a >> b;
    vector<string> ss;
    REP(i,HW) {
        if (i < HW /2) ss.emplace_back(string(HW,B));
        else ss.emplace_back(string(HW,W));
    }

    int x = 0, y = 0;
    int i = a-1;
    while(i > 0) {
        ss[y][x] = W;
        x += 2;
        if (x >= HW) {
            y += 2;
            x = 0;
        }
        i--;
    }

    x = 0, y = HW-1;
    i = b-1;
    while(i > 0) {
        ss[y][x] = B;
        x += 2;
        if (x >= HW) {
            y -= 2;
            x = 0;
        }
        i--;
    }

    cout << HW << " " << HW << '\n';
    REP(i,HW) cout << ss[i] << '\n';

    return 0;
}


// Problem : C - Snuke Festival
// Contest : AtCoder - AtCoder Beginner Contest 077
// URL : https://atcoder.jp/contests/abc077/tasks/arc084_a
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
#include <bits/stdc++.h>
using namespace std;

/* DEBUGGING */
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define deb(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define deb(x...)
#endif

/* MACROS */
typedef long long int ll;

typedef pair<int, int> pii;
typedef pair<ll,ll> pll;

typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;

typedef map<int,int> mii;

#define  ff          first
#define  ss          second
#define  pb          push_back
#define  IOS         ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define  lb          lower_bound
#define  ub          upper_bound
#define  all(x)      (x).begin(), (x).end()
#define  ps(x,y)     fixed<<setprecision(y)<<x
#define  setbit(x)   __builtin_popcountll(x)
#define  rep(i,a,b)  for(int i=a ; i<b ; ++i)
#define  repr(i,a,b) for(int i=a ; i>=b ; --i)

/* CONSTANTS */
#define PI 3.141592653589793
const ll MOD = 1e9 + 7;
const ll INF = 1000000000;
const ll MAX_N = 2e5 + 2;

// #define cerr if(false)cerr
/* CODE STARTS HERE */

void solve(){
    int n; cin >> n;
    vi a(n),b(n),c(n);
    rep(i,0,n) cin >> a[i];
    rep(i,0,n) cin >> b[i];
    rep(i,0,n) cin >> c[i];

    sort(all(a)) , sort(all(c));
    ll ans = 0,temp1,temp2;

    rep(i,0,n){
        auto it1 = lb(all(a),b[i]) - a.begin();
        auto it2 = ub(all(c),b[i]) - c.begin();

        temp1 = it1, temp2 = n - it2;
        ans += (temp1 * temp2);
    }

    cout << ans;
}

int main(){
    IOS;
    solve();
}

#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i < b; i++)
#define Rep(i, a, b) for(int i = a; i <= b; i++)
#define repr(i, a, b) for(int i = a; i >= b; i--)
#define _GLIBCXX_DEBUG
#define Vl vector<ll>
#define Vs vector<string>
#define Vp vector<pair<ll, ll>>
#define P pair<ll, ll>
using ll = long long;
#define ALL(v) (v).begin(),(v).end()
#define endl "\n"
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define co(x) cout << x << endl
#define coel cout << endl
#define pb push_back
#define sz(v) ((ll)(v).size())
using namespace std;
const double pi = acos(-1.0);
const ll MOD = 1e9 + 7;
const ll INF = 1LL << 60;
#define pp pair<ll, pair<ll, ll>>
#define fi first
#define se second

////////////////////////////////////////////////////////

int main() {
    ll n; cin >> n;
    string s, t; cin >> s >> t;
    ll a = 2*n;
    ll ans = a;
    rep(i, 0, n){
        string ss = s.substr(n-1-i, i+1), tt = t.substr(0, i+1);
        if(ss == tt) chmin(ans, a-i-1);
    }

    co(ans);

    return 0;
}


#include <iostream>
#include<algorithm>
#include<string>
#include <cmath>
#include <vector>
#include <map>
#include <cstdio>
#include <iomanip>
#pragma region Macros
#define int long long
#define double long double
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979323846;
#define rep(i,n) for(int i=0;i<n;i++)
#define REP(i,n) for(int i=1;i<=n;i++)
#define LAST(x) x[x.size()-1]
#define ALL(x) (x).begin(),(x).end()
#define swap(a,b) (a += b,b = a - b,a -= b)
#define CEIL(a,b) ((a+b-1)/b)
int FACT(int a) {
	if (a == 0)
		return 1;
	else
		return a * FACT(a - 1);
}
int nPr(int n, int r) {
	int s = n-r+1;
	int sum = 1;
	for(int i =s;i<=n;i++)
		sum *= i;
	return sum;
}
//int nCr1(int n, int r)
//int nCr2(int n, int r)
int GCD(int a, int b) // assuming a,b >= 1
{
	if (a < b)
		swap(a, b);
	if (b == 0)
		return a;
	if (a % b == 0)
		return b;
	return GCD(b, a % b);
}
int LCM(int a, int b) // assuming a,b >= 1
{
	return  a * b / GCD(a, b);
}
double LOG(int a, int b) {
	return log(b) / log(a);
}
inline bool BETWEEN(int x, int min, int max) {
	if (min <= x && x <= max)
		return true;
	else
		return false;
}

using namespace std;
#pragma endregion
signed main() {
	int x, y,z=0;
	cin >> x >> y;
	if (x == 1 && y == 1)
		cout << 1000000;
	else
		cout << max(z, 100000 * (4 - x)) + max(z, 100000 * (4 - y));
}

#include <bits/stdc++.h>
using namespace std;
#define lli long long int
#define uli unsigned long long int
#define INF 999999999999999999
#define rep(i,m,n) for(lli i = m;i < n;i++)
#define rrep(i,m,n) for(lli i=m-1;i>=n;i--)
#define pb(n) push_back(n)
#define UE(N) N.erase(unique(N.begin(),N.end()),N.end());
#define Sort(n) sort(n.begin(), n.end())
#define Rev(n) reverse(n.begin(),n.end())
#define Out(S) cout << S << endl
#define NeOut(S) cout << S
#define HpOut(S) cout << setprecision(25) << S << endl
#define Vec(K,L,N,S) vector<L> K(N,S)
#define DV(K,L,N,M,S) vector<vector<L>> K(N,vector<L>(M,S))
#define TV(K,L,N,M,R,S) vector<vector<vector<L>>> K(N,vector<vector<L>>(M,vector<L>(R,S)))
#define pint pair<lli,lli>
#define paf(L,R) pair<L,R>
#define mod 1000000007
#define MAX 510000
#define ALL(a)  a.begin(),a.end()
#define chmax(a, b) a = (((a)<(b)) ? (b) : (a))
#define chmin(a, b) a = (((a)>(b)) ? (b) : (a))
int main(){
  lli A,B,C,D,E,F,N,M,K,L,X,Y,Z,H,W,sum=0,num=0,flag=0;string S,T;
  cin >> X >> Y;
  if(X==3)sum+=100000;
  if(X==2)sum+=200000;
  if(X==1)sum+=300000;
  if(Y==3)sum+=100000;
  if(Y==2)sum+=200000;
  if(Y==1)sum+=300000;
  if(X==Y&&Y==1)sum+=400000;
  Out(sum);
}


#include <bits/stdc++.h>
#define DAU  ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define PLEC exit(0);
using namespace std;
vector<int> v;
int x, y, res(2019);
int main() {
    DAU
    cin >> x >> y;
    for (int i = x; i <= min(x + 2020, y); ++i)
        v.emplace_back(i % 2019);
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
    for (size_t i = 0; i < v.size(); ++i)
        for (size_t j = i + 1; j < v.size(); ++j)
            res = min(res, (v[i] * v[j]) % 2019);
    cout << res;
    PLEC
}

#include <bits/stdc++.h>

using namespace std;

namespace program
{
	namespace IO
	{
		struct input_t
		{
			static const int BUF_SIZ = 500000;
			FILE *f;
			char Buf[BUF_SIZ], *p, *pend;
			input_t(FILE *_f) : f(_f), p(Buf), pend(Buf) {}
			~input_t() { fclose(f); }
			char getchar();
			template <typename T>
			T read();
		};

		char input_t::getchar()
		{
			if (p >= pend)
			{
				p = Buf;
				pend = Buf + fread(Buf, sizeof(char), BUF_SIZ, f);
				if (p >= pend)
					return EOF;
			}
			return *p++;
		}

		template <typename T>
		T input_t::read()
		{
			T s = 0;
			int fl = 0;
			char ch;
			while (!isdigit(ch = getchar()))
				fl ^= (ch == '-');
			do
				s = s * 10 + ch - '0';
			while (isdigit(ch = getchar()));
			return fl ? -s : s;
		}

		struct output_t
		{
			static const int BUF_SIZ = 500000;
			FILE *f;
			char Buf[BUF_SIZ], *p, *const pend;
			output_t(FILE *_f) : f(_f), p(Buf), pend(Buf + BUF_SIZ) {}
			~output_t()
			{
				fwrite(Buf, sizeof(char), p - Buf, f);
				fclose(f);
			}
			void putchar(char ch);
			template <typename T>
			void write(T x);
			void puts(const char *ch);
		};

		void output_t::putchar(char ch)
		{
			*p++ = ch;
			if (p >= pend)
			{
				fwrite(Buf, sizeof(char), p - Buf, f);
				p = Buf;
			}
		}

		template <typename T>
		void output_t::write(T x)
		{
			static char St[30];
			char *top = St;
			if (x < 0)
			{
				putchar('-');
				x = -x;
			}
			do
				*top++ = x % 10 + '0';
			while (x /= 10);
			while (top > St)
				putchar(*--top);
		}

		void output_t::puts(const char *ch)
		{
			while (*ch)
				putchar(*ch++);
			putchar('\n');
		}
	}

	IO::input_t input(stdin);
	IO::output_t output(stdout);

	typedef long long big;

	const int MAXN = 100000;

	template <typename T>
	vector<T> &operator*=(vector<T> &A, vector<int> B)
	{
		vector<T> C = A;
		for (int i = 0; i < A.size(); i++)
			A[i] = C[B[i]];
		return A;
	}

	template <typename T1, typename T2>
	void qpow(T1 &S, T2 X, big n)
	{
		while (n)
		{
			if (n & 1)
				S *= X;
			X *= X;
			n >>= 1;
		}
	}

	void work()
	{
		int n = input.read<int>(), m;
		big k;
		vector<big> X;
		vector<int> C;
		for (int i = 0; i < n; i++)
		{
			X.push_back(input.read<big>());
			C.push_back(i);
		}
		for (int i = n - 1; i > 0; i--)
			X[i] -= X[i - 1];
		m = input.read<int>();
		k = input.read<big>();
		while (m--)
		{
			int x = input.read<int>();
			swap(C[x - 1], C[x]);
		}
		qpow(X, C, k);
		for (int i = 1; i < n; i++)
			X[i] += X[i - 1];
		for (int i = 0; i < n; i++)
		{
			output.write(X[i]);
			output.puts(".0");
		}
	}
}

int main()
{
	program::work();
	return 0;
}


#include <algorithm>
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <math.h>

// ===============================================================

using namespace std;
using ll = long long;
using vl = vector<long long>;
using vll = vector<vector<long long>>;
using vs = vector<string>;
using vc = vector<char>;
using vcc = vector<vector<char>>;
using vm = vector<short>;
using vmm = vector<vector<short>>;
using pii = pair<int, int>;
using psi = pair<string, int>;
using ld = long double;
using ull = unsigned long long;

// ===============================================================

ll gcd(ll a, ll b)
{
	if (a % b == 0)
	{
		return(b);
	}
	else
	{
		return(gcd(b, a % b));
	}
}
//最大公約数
ll lcm(ll a, ll b)
{
	return a * b / gcd(a, b);
}
//最小公倍数
ll box(double a)
{
	ll b = a;
	return b;
}
//切り捨て
ll fff(double a)
{
	ll b = a + 0.5;
	return b;
}
//四捨五入
ll sum(ll n) {
	return (1 + n) * n / 2;
}
//1から整数nまでの合計
bool prime(ll a)//素数判定、primeならtrue,違うならfalse
{
	if (a < 2) return false;
	else if (a == 2) return true;
	else if (a % 2 == 0) return false;
	double sqrtNum = sqrt(a);
	for (int i = 3; i <= sqrtNum; i += 2)
	{
		if (a % i == 0)
		{
			return false;
		}
	}

	// 素数である
	return true;
}
//素数判定

// ===============================================================

int main() {
	ll n; cin >> n;
	ll q; cin >> q;
	string a;
	cin >> a;
	vl x(q);
	vl y(q);
	for (int i = 0; i < q; i++) {
		cin >> x[i] >> y[i];
	}
	vector<ll> dataa(n);
	vector<ll> datab(n);
	ll count = 0;
	for (int i = 0; i < n - 1; i++) {
		if (a.substr(i, 2) == "AC") {
			count++;
			dataa[i] = count;
			datab[i + 1] = count;
		}
		else {
			dataa[i] = datab[i + 1] = count;
		}
	}
	for (int i = 0; i < q; i++) {
		cout << datab[y[i] - 1] - datab[x[i] - 1] << endl;
	}
}

#include <bits/stdc++.h>
using namespace std;

struct StQuery
{
  StQuery() : m_nLeft(0), m_nRigt(0) { }

  int m_nLeft;
  int m_nRigt;
};

void input(string& rsStr, vector<StQuery>& rvoQuery)
{
  int nStrSiz, nQuerySiz;
  cin >> nStrSiz >> nQuerySiz;
  rvoQuery.resize(nQuerySiz);

  cin >> rsStr;

  for (StQuery& roQuery : rvoQuery)
    cin >> roQuery.m_nLeft >> roQuery.m_nRigt;
}

void calcSubStrACCnt(string sStr, const vector<StQuery>& cnrvoQuery)
{
  vector<int> vnCumlSum(sStr.size() + 1);      // 累積和

  //vnCumlSum_ix 0 1 2 3 4 5 6 7 8
  //sStr_pos      1 2 3 4 5 6 7 8
  //sStr          A C A C T A C G
  //sStr_ix       0 1 2 3 4 5 6 7
  for (int nBgn = 0; nBgn < vnCumlSum.size() - 1; nBgn++)
  {
    vnCumlSum[ nBgn + 2 ] = vnCumlSum[ nBgn + 1 ];
    if (sStr[nBgn] == 'A' && sStr[nBgn + 1] == 'C')
      vnCumlSum[ nBgn + 2 ]++;
  }

 for (int i = 0; i < cnrvoQuery.size(); i++)
  {
    cout << vnCumlSum[ cnrvoQuery[i].m_nRigt ] - vnCumlSum[ cnrvoQuery[i].m_nLeft ];
    cout << endl;
  }
}

int main()
{
  string sStr;
  vector<StQuery> voQuery;

  input(sStr, voQuery);
  calcSubStrACCnt(sStr, voQuery);

  return 0;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<pii,int> piii;
typedef pair<ll,ll> pll;

#define reps(i,f,n) for(int i = int(f); i <= int(n); i++)
#define rep(i,n) reps(i,0,int(n)-1)
#define rrep(i,n) for(int i = n-1; i >= 0; i--)

#define all(x) (x).begin(),(x).end()
#define X first
#define Y second

#define sz size()
#define eb emplace_back

int memo[64][64];

int main(void){
  while(1){
    int n,p;
    int pl[64] = {0};
    int ans = -1;
    int bowl;
    cin >> n >> p;
    bowl = n;
    if(n+p==0)break;
    if(memo[n][p] == 0){
      bowl = p;
      rep(i,1000000){
        if(bowl){
          bowl--;
          pl[(i%n)]++;
          if(pl[i%n] == p){ans = i%n;break;}
        }else{
          bowl = pl[i%n];
          pl[i%n] = 0;
        }
      }
      cout << ans << endl;
      memo[n][p] = ans;
    }else{
      cout << memo[n][p] << endl;
    }
  }
  return 0;
}

#include <bits/stdc++.h>
#define REP(i,n,N) for(int i=n;i<N;i++)
#define MEM(a,n) memset(a,n,sizeof(a))
#define p(S) cout<<(S)<<endl
using namespace std;

int main(){
	int n,p;
	while(cin>>n>>p,n){
		int a[50],center=p;
		MEM(a,0);
		int ans;
		REP(i,0,n){
			if(center>0) {
				a[i]++;
				center--;
			}
			else{
				center+=a[i];
				a[i]=0;
			}
			if(center==0){
				bool flag=true;
				REP(j,0,n){
					if(i==j) continue;
					if(a[j]!=0){
						flag=false;
						break;
					}
				}
				if(flag) {
					ans=i;
					break;
				}
			}
			if(i==n-1) i=-1;
		}
		p(ans);
	}
	return 0;
}