#include <bits/stdc++.h>
using namespace std;
template <class T>
T sqr(T a) {
  return a * a;
}
vector<int> pr;
bool was[1 << 20] = {0};
void calc() {
  const int n = 1 << 20;
  for (int i = 2; i < n; ++i) {
    if (was[i]) continue;
    pr.push_back(i);
    for (int j = i; j < n; j += i) was[j] = 1;
  }
}
int upperb(int x) {
  int l = 0, r = (int)(pr).size() - 1;
  int res = r;
  while (l <= r) {
    int m = (l + r) >> 1;
    if (pr[m] == x) return m;
    if (pr[m] > x) {
      res = m;
      r = m - 1;
    } else
      l = m + 1;
  }
  return res;
}
int a[500][500];
int d[500][500] = {0};
int s[500] = {0};
int r[500] = {0};
int main() {
  calc();
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      scanf("%d", &a[i][j]);
      int u = upperb(a[i][j]);
      d[i][j] = pr[u] - a[i][j];
    }
  }
  int res = 1 << 30;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      s[i] += d[i][j];
      r[j] += d[i][j];
    }
  }
  for (int i = 0; i < n; ++i) res = min(res, s[i]);
  for (int i = 0; i < m; ++i) res = min(res, r[i]);
  cout << res << endl;
  return 0;
}
