#include <bits/stdc++.h>
using namespace std;
const int N = 2e5;
int vis[N + 2], r[502], c[502];
void init() {
  for (int i = 2; i * i <= N; ++i)
    if (!vis[i]) {
      for (int j = i * i; j <= N; j += i) vis[j] = -1;
    }
  vis[0] = vis[1] = -1;
  for (int i = N; i; --i)
    if (vis[i]) vis[i] = vis[i + 1] + 1;
}
int main() {
  init();
  int n, m, x;
  cin >> n >> m;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      cin >> x;
      r[i] += vis[x];
      c[j] += vis[x];
    }
  int res = 500 * N;
  for (int i = 1; i <= n; ++i) res = min(res, r[i]);
  for (int j = 1; j <= m; ++j) res = min(res, c[j]);
  cout << res << endl;
  return 0;
}
