#include <bits/stdc++.h>
#pragma GCC optimize "trapv"
using namespace std;
std::vector<long long int> v;
const long long int x = 1000007;
void fun() {
  bool prime[x + 1];
  memset(prime, true, sizeof(prime));
  for (long long int p = 2; p * p <= x; p++) {
    if (prime[p] == true) {
      for (long long int i = p * p; i <= x; i += p) prime[i] = false;
    }
  }
  for (long long int p = 2; p <= x; p++)
    if (prime[p]) v.push_back(p);
}
int32_t main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  ;
  long long int n, m;
  cin >> n >> m;
  long long int a[n][m];
  for (long long int i = 0; i < n; i++) {
    for (long long int j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  fun();
  long long int ans = INT_MAX;
  for (long long int i = 0; i < n; i++) {
    long long int s = 0;
    for (long long int j = 0; j < m; j++) {
      if (binary_search(v.begin(), v.end(), a[i][j]) == 0) {
        long long int u = upper_bound(v.begin(), v.end(), a[i][j]) - v.begin();
        s += v[u] - a[i][j];
      }
    }
    ans = min(ans, s);
  }
  for (long long int i = 0; i < m; i++) {
    long long int s = 0;
    for (long long int j = 0; j < n; j++) {
      if (binary_search(v.begin(), v.end(), a[j][i]) == 0) {
        long long int u = upper_bound(v.begin(), v.end(), a[j][i]) - v.begin();
        s += v[u] - a[j][i];
      }
    }
    ans = min(ans, s);
  }
  cout << ans << endl;
  return 0;
}
