#include <bits/stdc++.h>
int main() {
  const int N = 100005;
  bool no[N] = {1, 1};
  int col[501], row[501], n, m, i, j, x;
  int vis[100005];
  memset(vis, 0, sizeof(vis));
  for (i = 2; i * i < N; ++i)
    for (j = i * i; j < N; j += i) no[j] = 1;
  for (int i = 0; i <= 100000; i++) {
    int k = 0;
    while (no[i + k]) k++;
    vis[i] = k;
  }
  while (scanf("%d %d", &n, &m) != EOF) {
    memset(col, 0, sizeof(col));
    memset(row, 0, sizeof(row));
    for (i = 0; i < n; ++i) {
      for (j = 0; j < m; ++j) {
        int k = 0;
        scanf("%d", &x);
        col[i] += vis[x];
        row[j] += vis[x];
      }
    }
    int mx = 500 * 500;
    for (int i = 0; i < n; i++) {
      if (col[i] < mx) mx = col[i];
    }
    for (int i = 0; i < m; i++) {
      if (row[i] < mx) mx = row[i];
    }
    printf("%d\n", mx);
  }
  return 0;
}
