#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
template <class c>
struct rge {
  c b, e;
};
template <class c>
rge<c> range(c i, c j) {
  return rge<c>{i, j};
}
template <class c>
auto dud(c* x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct debug {
  template <class c>
  debug& operator<<(const c&) {
    return *this;
  }
};
bool isPrime[1000005];
void sie(long long n) {
  memset(isPrime, true, sizeof isPrime);
  isPrime[0] = isPrime[1] = false;
  for (long long i = 2; i * i <= n; i++) {
    if (isPrime[i]) {
      for (long long j = i * i; j <= n; j += i) {
        isPrime[j] = false;
      }
    }
  }
}
vector<long long> pr;
long long cnti[505], cntj[505];
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  sie(1000004);
  for (long long i = 2; i < 1000005; i++) {
    if (isPrime[i]) pr.push_back(i);
  }
  long long n, m;
  cin >> n >> m;
  vector<vector<long long> > a(n, vector<long long>(m));
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
      long long ind =
          lower_bound((pr).begin(), (pr).end(), a[i][j]) - pr.begin();
      cnti[i] += (pr[ind] - a[i][j]);
      cntj[j] += (pr[ind] - a[i][j]);
    }
  }
  long long mn = 1e9;
  for (long long i = 0; i < n; i++) {
    mn = min(mn, cnti[i]);
  }
  for (long long i = 0; i < m; i++) {
    mn = min(mn, cntj[i]);
  }
  cout << mn << "\n";
  return 0;
}
