#include <bits/stdc++.h>
using namespace std;
const int maxn = 500005;
int vis[maxn];
int q[maxn];
int Map[509][5009];
int sum = 0;
void Prime() {
  for (int i = 2; i * i <= maxn; i++) {
    for (int j = 2; j <= maxn; j++)
      if (!vis[i] && i * j <= maxn) {
        vis[i * j] = 1;
      }
  }
  vis[1] = 1;
  vis[0] = 1;
  for (int i = 2; i < maxn; i++)
    if (!vis[i]) q[sum++] = i;
}
const int INF = 0xfffffff;
int erfen(int key) {
  int l = 0;
  int r = sum;
  while (l <= r) {
    int mid = (l + r) >> 1;
    if (key > q[mid] && key < q[mid + 1]) return mid + 1;
    if (key > q[mid]) {
      l = mid + 1;
    }
    if (key < q[mid]) r = mid - 1;
  }
}
int main() {
  int n, m;
  Prime();
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      scanf("%d", &Map[i][j]);
    }
  int Min = INF;
  for (int i = 0; i < n; i++) {
    int ans = 0;
    for (int j = 0; j < m; j++) {
      int t = Map[i][j];
      if (!vis[t]) continue;
      if (t < 2)
        ans += 1;
      else {
        int c = erfen(t);
        ans += q[c] - t;
      }
    }
    if (ans < Min) Min = ans;
  }
  for (int j = 0; j < m; j++) {
    int ans = 0;
    for (int i = 0; i < n; i++) {
      int t = Map[i][j];
      if (!vis[t]) continue;
      if (t < 2)
        ans += 1;
      else {
        int c = erfen(t);
        ans += q[c] - t;
      }
    }
    if (ans < Min) Min = ans;
  }
  cout << Min << endl;
  return 0;
}
