#include <bits/stdc++.h>
using namespace std;
const int maxmn = 505;
long long a[maxmn][maxmn];
long long luu1[maxmn][maxmn];
bool k[1000005];
long long maxx = 1e9;
void readquick() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
int main() {
  readquick();
  vector<long long> luu;
  memset(k, true, sizeof k);
  for (int i = 2; i <= sqrt(1000000); i++) {
    if (k[i] == true) {
      for (int j = i * i; j <= 1000000; j += i) {
        k[j] = false;
      }
    }
  }
  for (int i = 2; i <= 1000000; i++) {
    if (k[i] == true) luu.push_back(i);
  }
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> a[i][j];
      int w = lower_bound(luu.begin(), luu.end(), a[i][j]) - luu.begin();
      luu1[i][j] = luu[w] - a[i][j];
    }
  }
  for (int i = 1; i <= n; i++) {
    long long tong = 0;
    for (int j = 1; j <= m; j++) {
      tong += luu1[i][j];
    }
    if (tong >= 0) {
      maxx = min(maxx, tong);
    }
  }
  for (int i = 1; i <= m; i++) {
    long long tong = 0;
    for (int j = 1; j <= n; j++) {
      tong += luu1[j][i];
    }
    if (tong >= 0) {
      maxx = min(maxx, tong);
    }
  }
  cout << maxx;
  return 0;
}
