#include <bits/stdc++.h>
using namespace std;
long fact(long int w) {
  long int k, p = 0, l = 0, r = w;
  if (w == 1)
    return 1;
  else {
    while (p != 1) {
      for (k = 2; k <= pow(w, .5); k++) {
        if (w % k == 0) {
          l = 1;
          k = pow(w, .5);
        }
      }
      if (l == 0)
        p = 1;
      else {
        l = 0;
        w++;
      }
    }
    return w - r;
  }
}
long long int isprime(long long int n) {
  if (n <= 1) return 0;
  if (n <= 3) return 1;
  if (n % 2 == 0 || n % 3 == 0) return 0;
  for (long long int i = 5; i * i <= n; i = i + 6)
    if (n % i == 0 || n % (i + 2) == 0) return 0;
  return 1;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long int n, m, i, j, g = 0, h = -1;
  ;
  cin >> n >> m;
  long int a[n][m], b[n][m], d[n][m], c[n + m];
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> a[i][j];
      b[i][j] = a[i][j];
      while (isprime(a[i][j]) == 0) {
        a[i][j]++;
      }
      d[i][j] = a[i][j] - b[i][j];
    }
  }
  for (i = 0; i < n; i++) {
    g = 0;
    for (j = 0; j < m; j++) {
      g = g + d[i][j];
    }
    if (h == -1)
      h = g;
    else
      h = min(h, g);
  }
  for (i = 0; i < m; i++) {
    g = 0;
    for (j = 0; j < n; j++) {
      g = g + d[j][i];
    }
    h = min(h, g);
  }
  cout << h;
  return 0;
}
