#include <algorithm>
#include <bitset>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <istream>
#include <limits>
#include <vector>

using ll = int64_t;


constexpr ll maxn = 1e3;
constexpr ll maxa = 10000100;

ll n, m;
ll arr[maxn + 5][maxn + 5];
ll cm[maxn + 5][maxn + 5];
ll cr[maxn + 5], ca[maxn + 5];
ll ans = std::numeric_limits<ll>::max();
ll np[maxa + 5];

std::bitset<10000105> bs;

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  std::cout.tie(nullptr);

  bs.set();
  bs.reset(0);
  bs.reset(1);

  for (ll i = 2; i * i <= maxa; ++i) {
    if (bs[i]) {
      for (ll j = i * i; j <= maxa; j += i) {
        bs[j] = false;
      }
    }
  }

  ll nnp = std::numeric_limits<ll>::max();
  for (ll i = maxa; i >= 0; --i) {
    if (bs[i]) {
      nnp = i;
    }
    np[i] = nnp;
  }

  std::cin >> n >> m;
  for (ll i = 0; i < n; i++) {
    for (ll j = 0; j < m; j++) {
      std::cin >> arr[i][j];

      if (arr[i][j] > maxa) {

        arr[i][j] = maxa;
      }
    }
  }

  for (ll i = 0; i < n; i++) {
    for (ll j = 0; j < m; j++) {
      cm[i][j] = np[arr[i][j]] - arr[i][j];
    }
  }

  for (ll i = 0; i < n; i++) {
    ll row_total = 0;
    for (ll j = 0; j < m; j++) {
      row_total += cm[i][j];
    }
    cr[i] = row_total;
  }

  for (ll j = 0; j < m; j++) {
    ll ct = 0;
    for (ll i = 0; i < n; i++) {
      ct += cm[i][j];
    }
    ca[j] = ct;
  }

  for (ll i = 0; i < n; i++) {
    for (ll j = 0; j < m; j++) {

      ll ccc =
          cr[i] + ca[j] + (bs[arr[i][j]] ? 0 : -cm[i][j]);
      if (ccc < ans) {
        ans = ccc;
      }
    }
  }

  std::cout << ans << '\n';
}