#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}, dy[] = {1, -1, 0, 0, 1, -1, -1, 1};
template <class T>
void cmin(T& a, T b) {
  if (b < a) a = b;
}
template <class T>
void cmax(T& a, T b) {
  if (b > a) a = b;
}
template <class T>
int len(const T& c) {
  return (int)c.size();
}
template <class T>
int len(char c[]) {
  return (int)strlen(c);
}
string itos(long n) {
  string s;
  while (n) {
    s += (n % 10 + 48);
    n /= 10;
  }
  reverse(s.begin(), s.end());
  return s;
}
long stoi(string s) {
  long n = 0;
  for (int i(0), _n(len(s)); i < _n; ++i) n = n * 10 + (s[i] - 48);
  return n;
}
long p(long n) {
  if (n == 2) return 1;
  if (n == 0 || n == 1 || n % 2 == 0) return 0;
  for (long j = 3; j <= sqrt(n); j += 2) {
    if (n % j == 0) return 0;
  }
  return 1;
}
long pr[100005] = {0};
int main() {
  for (int i(0), _n(100000); i < _n; ++i) {
    if (p(i)) pr[i] = 1;
  }
  pr[100003] = 1;
  long r, c, cc, s, rr, ar[600][600];
  cin >> r >> c;
  for (int i(0), _n(r); i < _n; ++i)
    for (int j(0), _n(c); j < _n; ++j) {
      cin >> s;
      rr = 0;
      while (1) {
        if (pr[s]) {
          break;
        }
        rr++;
        s++;
      }
      ar[i][j] = rr;
    }
  long res = 1000000000;
  for (int i(0), _n(r); i < _n; ++i) {
    cc = 0;
    for (int j(0), _n(c); j < _n; ++j) {
      cc += ar[i][j];
    }
    cmin(res, cc);
  }
  for (int i(0), _n(c); i < _n; ++i) {
    cc = 0;
    for (int j(0), _n(r); j < _n; ++j) {
      cc += ar[j][i];
    }
    cmin(res, cc);
  }
  cout << res << endl;
  return 0;
}
