#include <bits/stdc++.h>
using namespace std;
const int N = 600;
long long n, m, a, b, ans, arr[2][N];
vector<long long> prms;
void build() {
  const int LIM = 1e6;
  bool num[LIM] = {};
  for (long long i = 2; i < LIM; ++i) {
    if (num[i]) continue;
    prms.push_back(i);
    for (long long j = i * i; j < LIM; j += i) num[j] = 1;
  }
}
int get(long long x) {
  long long i = upper_bound(prms.begin(), prms.end(), x) - prms.begin();
  if (i > 0 && prms[i - 1] == x) return 0;
  return (prms[i] - x);
}
int main() {
  cin.sync_with_stdio(0);
  build();
  cin >> n >> m;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> a;
      b = get(a);
      arr[0][i] += b;
      arr[1][j] += b;
    }
  }
  ans = arr[0][0];
  for (int i = 0; i < n; ++i) ans = min(ans, arr[0][i]);
  for (int j = 0; j < m; ++j) ans = min(ans, arr[1][j]);
  printf("%lld", ans);
  return 0;
}
