#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using pi = pair<int, int>;
using ll = long long int;
template <typename T1, typename T2, typename T3>
T1 modpow(T1 _a, T2 p, T3 mod) {
  assert(p >= 0);
  ll ret = 1, a = _a;
  if (a < 0) {
    a %= mod;
    a += mod;
  }
  if (a >= mod) {
    a %= mod;
  }
  for (; p > 0; p /= 2) {
    if (p & 1) ret = ret * a % mod;
    a = a * a % mod;
  }
  return ret;
}
constexpr int dx[] = {-1, 0, 1, 0, 1, 1, -1, -1};
constexpr int dy[] = {0, -1, 0, 1, 1, -1, 1, -1};
constexpr auto PI = 3.14159265358979323846L;
constexpr auto oo = numeric_limits<int>::max() / 2 - 2;
constexpr auto eps = 1e-6;
constexpr auto mod = 1000000007;
constexpr int mx_n = 502, mx_a = 101005;
int mat[mx_n][mx_n];
int notprime[mx_a], inc[mx_a];
int n, m;
void pre() {
  notprime[0] = notprime[1] = 1;
  for (int i = 2; i * i < mx_a; ++i)
    if (!notprime[i]) {
      for (int j = i * i; j < mx_a; j += i) notprime[j] = 1;
    }
  for (int i = mx_a - 2; i >= 0; --i) {
    if (notprime[i]) inc[i] = 1 + inc[i + 1];
  }
  for (int i = ((0)), _i = ((15) - 1); i <= _i; ++i)
    ;
}
int costRow(int i) {
  int ret = 0;
  for (int j = ((0)), _j = ((m)-1); j <= _j; ++j) ret += mat[i][j];
  return ret;
}
int costCol(int j) {
  int ret = 0;
  for (int i = ((0)), _i = ((n)-1); i <= _i; ++i) ret += mat[i][j];
  return ret;
}
int main() {
  pre();
  cin >> n >> m;
  for (int i = ((0)), _i = ((n)-1); i <= _i; ++i)
    for (int j = ((0)), _j = ((m)-1); j <= _j; ++j) {
      cin >> mat[i][j];
      mat[i][j] = inc[mat[i][j]];
      ;
    }
  int ans = oo;
  for (int i = ((0)), _i = ((n)-1); i <= _i; ++i) ans = min(ans, costRow(i));
  for (int j = ((0)), _j = ((m)-1); j <= _j; ++j) ans = min(ans, costCol(j));
  cout << ans << endl;
  return 0;
}
