#include<bits/stdc++.h>
#define ll long long
#define pll pair<ll,ll>
#define F first
#define S second
#define mp make_pair
using namespace std;
const int N=1005;
int n,k,a[N][N],sum[N][N],ans=1e9;
bool check(int mid)
{
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+(a[i][j]<=mid);
		}
	}
	for(int i=k;i<=n;i++)
	{
		for(int j=k;j<=n;j++)
		{
			int calc=sum[i][j]-sum[i][j-k]-sum[i-k][j]+sum[i-k][j-k];
			if(calc>=(k*k+1)/2)return true;
		}
	}
	return false;
}
int main()
{
	cin>>n>>k;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++) 
		{
			cin>>a[i][j];
		}
	}
	int l=0,r=1e9;
	while(l<=r)
	{
		int mid=(l+r)>>1;
		if(check(mid))
			r=mid-1;
		else
			l=mid+1;
	}
	cout<<r+1; 
	return 0;
}
#include "bits/stdc++.h"

using namespace std;

typedef long long ll;

const ll INFLL = 2e18 + 5;

ll good(string x, ll n){
	ll ans = 0;
	for(char c: x){
		if(ans > INFLL / n)	return INFLL;
		ans *= n;
		ans += int(c - '0');
	}
	return ans;
}

int main(){
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t = 1;	//cin >> t;
	for(int tt = 0; tt < t; tt++){
		string x;	cin >> x;
		ll m;	cin >> m;
		int d = 0, n = (int) x.size();
		for(int i = 0; i < n; i++){
			d = max(d, x[i] - '0');
		}
		if((int) x.size() == 1){
			ll xd = (x[0] - '0');
			if(xd <= m)	cout << "1\n";
			else cout << "0\n";
		}else{
			ll lo = d, hi = m + 1;
			while(hi - lo > 1){
				ll mid = (lo + hi) / 2;
				if(good(x, mid) <= m){
					lo = mid;
				}else{
					hi = mid;
				}
			}
			cout << lo - d << "\n";
		}
	}
}
