#include <bits/stdc++.h>
using namespace std;
const char nl = '\n';
const char gg = ' ';
const int M = 1e5 + 5;
bool mark[M];
vector<int> prime;
void sieve() {
  int i, j, n;
  for (i = 3; i * i <= M; i += 2) {
    if (!mark[i]) {
      for (j = i * i; j < M; j += i + i) mark[j] = true;
    }
  }
  prime.push_back(2);
  for (i = 3; i <= 100003; i += 2) {
    if (!mark[i]) prime.push_back(i);
  }
}
void solve() {
  int n, m, i, j, idx, dif, mx = 0, ans = INT_MAX, sm = 0;
  cin >> n >> m;
  int ar[n][m];
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> ar[i][j];
      mx = max(mx, ar[i][j]);
    }
  }
  idx = upper_bound(prime.begin(), prime.end(), mx) - prime.begin();
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      dif = *lower_bound(prime.begin(), prime.begin() + idx, ar[i][j]);
      sm += (dif - ar[i][j]);
    }
    ans = min(ans, sm);
    if (sm == 0) break;
    sm = 0;
  }
  sm = 0;
  for (j = 0; j < m; j++) {
    for (i = 0; i < n; i++) {
      dif = *lower_bound(prime.begin(), prime.begin() + idx, ar[i][j]);
      sm += (dif - ar[i][j]);
    }
    ans = min(ans, sm);
    if (sm == 0) break;
    sm = 0;
  }
  cout << ans << nl;
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0);
  ;
  sieve();
  int t = 1;
  while (t--) solve();
  return 0;
}
