#ifdef _DEBUG
#define _GLIBCXX_DEBUG
#endif
#if __has_include(<atcoder/all>)
#include <atcoder/all>
#endif
#include <bits/stdc++.h>
using namespace std;
#define int long long
using ll = long long;
using ld = long double;
using P = pair<int, int>;
#define rep(i, a, b) for(int i = (int)(a); i <= (int)(b); i++)
#define rrep(i, a, b) for(int i = (int)(a); i >= (int)(b); i--)
const int MOD = 1000000007;
const int MOD2 = 998244353;
const ll INF = 1e18;
const ld PI = acos(-1);

signed main() {
    int N,K;
    cin >> N >> K;
    vector<vector<int>> A(N,vector<int>(N));
    rep(i,0,N-1) rep(j,0,N-1) cin >> A[i][j];
    int ok=INF,ng=-1;
    while(abs(ok-ng)>1){
        int mid=(ok+ng)/2;
        vector<vector<int>> newA(N+K,vector<int> (N+K,0));
        rep(i,0,N-1){
            rep(j,0,N-1){
                if(A[i][j]<=mid){
                    newA[i][j]++;
                    newA[i][j+K]--;
                    newA[i+K][j]--;
                    newA[i+K][j+K]++;
                }
            }
        }
        rep(i,0,N+K-1){
            rep(j,0,N+K-1){
                if(i&&j) newA[i][j]+=newA[i][j-1]+newA[i-1][j]-newA[i-1][j-1];
                else if(i) newA[i][j]+=newA[i-1][j];
                else if(j) newA[i][j]+=newA[i][j-1];
            }
        }
        bool isok=false;
        int base=(K*K+1)/2;
        rep(i,0,N-1){
            rep(j,0,N-1){
                //cout << newA[i][j] << endl;
                if(newA[i][j]>=base){
                    isok=true;
                }
            }
        }
        if(isok){
            ok=mid;
        }
        else{
            ng=mid;
        }
    }
    cout << ok << endl;
}
#include <cstdio>
#include <iostream>
#include <map>
#include <queue>
#include <vector>
#include <stack>
#include <algorithm>
#include <cmath>

typedef long long ll;

using namespace std;

ll Atoi(string s, ll radix, ll m)    
{
	ll ans = 0;
	for (ll i = 0; i < s.size(); i++)
	{
		char t = s[i];
		if (ans > m/radix)
			return 0;
		ans = ans * radix + t - '0';
	}
	return ans  <= m;
}

int main()
{
	string x;
	ll m;
	cin >> x >> m;

	if (x.size() == 1) {
		cout << Atoi(x, 10, m) << endl;
		return 0;
	}

	ll d = *max_element(x.begin(), x.end()) - '0' + 1;
	ll l = d, r = m;
	ll ans = 0;
	for (; l<=r; ) {
		ll mid = (l + r) / 2;
		if (Atoi(x, mid,m)) {
			ans = mid;
			l = mid + 1;
			
		}
		else {
			r = mid - 1;
		}
	}
	//cout << ans << " " << d << endl;
	if (d > ans) {
		cout << 0 << endl;
	}
	else {
		cout << ans - d + 1 << endl;
	}
}