#include <bits/stdc++.h>
using namespace std;
template <typename T>
T sgn(T x) {
  return x < 0 ? -1 : x != 0;
}
template <typename T>
T gcd(T a, T b) {
  return a ? gcd(b % a, a) : b;
}
void reads(string& x) {
  char kk[((long long)5e2 + 123)];
  scanf("%s", kk);
  x = kk;
}
long long n, m, ans;
long long v, r[((long long)5e2 + 123)], c[((long long)5e2 + 123)];
long long lp[(long long)1e6 + 1];
vector<long long> pr;
void sieve() {
  for (long long i = 2; i <= 1e6; ++i) {
    if (lp[i] == 0) {
      lp[i] = i;
      pr.push_back(i);
    }
    for (long long j = 0;
         j < (long long)pr.size() && pr[j] <= lp[i] && i * pr[j] <= 1e6; ++j)
      lp[i * pr[j]] = pr[j];
  }
}
void solve() {
  sieve();
  scanf("%lld %lld", &n, &m);
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) {
      scanf(" %lld", &v);
      v = (*lower_bound(pr.begin(), pr.end(), v) - v);
      r[i] += v;
      c[j] += v;
    }
  ans = 1e9;
  for (long long i = 0; i < n; i++) ans = min(ans, r[i]);
  for (long long i = 0; i < m; i++) ans = min(ans, c[i]);
  printf("%lld\n", ans);
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  while (t--) solve();
}
