#include <bits/stdc++.h>
using namespace std;
int pr[200000], pi;
int vis[200000];
void civ() {
  int i, j;
  pr[pi++] = 2;
  vis[1] = vis[0] = 1;
  for (i = 4; i < 110000; i += 2) vis[i] = 1;
  for (i = 3; i < 110000; i += 2) {
    if (!vis[i]) {
      pr[pi++] = i;
      if (i < 1000) {
        for (j = i * i; j < 110000; j += 2 * i) {
          vis[j] = 1;
        }
      }
    }
  }
  int cnt;
  for (i = pr[pi - 1]; i >= 0; i--) {
    cnt++;
    if (!vis[i]) cnt = 0;
    vis[i] = cnt;
  }
}
int a[600][600];
int main() {
  civ();
  int n, m, i, j;
  scanf("%d %d", &n, &m);
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++) {
      scanf("%d", &a[i][j]);
      a[i][j] = vis[a[i][j]];
    }
  int ans = 900000000;
  int sum;
  for (i = 0; i < n; i++) {
    sum = 0;
    for (j = 0; j < m; j++) {
      sum += a[i][j];
    }
    ans = min(ans, sum);
  }
  for (i = 0; i < m; i++) {
    sum = 0;
    for (j = 0; j < n; j++) {
      sum += a[j][i];
    }
    ans = min(ans, sum);
  }
  printf("%d\n", ans);
  return 0;
}
