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

ll solve() {
    ll A, B;
    cin >> A >> B;
    ll d = B-A;
    ll ans = 0;
    for ( ll d = B-A; d > 0; d-- ) {
        if ( B/d != (A%d==0 ? A/d : (A/d+1)) ) {
            return d;
        }
    }

    return 1;
}

int main() {
    auto ans = solve();
    cout << ans << "\n";
    return 0;
}
#include <bits/stdc++.h>

using namespace std;
// using namespace __gnu_pbds;

typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vii;
typedef vector<vi> vvi;
typedef vector<pll> vll;
typedef vector<vl> vvl;

#define fori(i, n) for (int i = 0; i < n; i++)
#define ford(i, n) for (int i = n - 1; i >= 0; i--)
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define repd(i, a, b) for (int i = a; i >= b; i--)
#define trav(x, a) for (auto &x : a)
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define eb emplace_back
#define endl '\n'
#define sz(a) (int)(a).size()
#define fi first
#define se second

clock_t time_p = clock();
void time_taken()
{
    time_p = clock() - time_p;
    cerr << "Time Taken : " << (float)(time_p) / CLOCKS_PER_SEC << "\n";
}

const ll mod = 1e9 + 7;
const ll INF = 1e18;

template <class T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;

int main()
{
    ios_base::sync_with_stdio(false), cin.tie(nullptr);

    int R, C;
    cin >> R >> C;

    vii adj[R * C];
    fori(i, R) fori(j, C - 1)
    {
        int from = i * C + j;
        int to = i * C + (j + 1);
        int w;
        cin >> w;
        adj[from].pb({to, w});
        adj[to].pb({from, w});
    }

    fori(i, R - 1) fori(j, C)
    {
        int from = i * C + j;
        int to = (i + 1) * C + j;
        int w;
        cin >> w;
        adj[from].pb({to, w});
    }

    min_heap<pair<ll, int>> pq;
    pq.push({0, 0});

    vl d(R * C, INF);
    d[0] = 0;
    while (!pq.empty())
    {
        auto [dis, at] = pq.top();
        pq.pop();
        auto [r, c] = make_pair(at / C, at % C);
        if (d[at] < dis)
            continue;
        for (auto [to, w] : adj[at])
        {
            if (d[to] > d[at] + w)
            {
                d[to] = d[at] + w;
                pq.push({d[to], to});
            }
        }

        for (int to = 0; to < r; to++)
        {
            int tto = to * C + c;
            int cost = r - to + 1;
            if (d[tto] > d[at] + cost)
            {
                d[tto] = d[at] + cost;
                pq.push({d[tto], tto});
            }
        }
    }

    cout << d.back() << endl;

    time_taken();
    return 0;
}