#include <bits/stdc++.h>
using namespace std;
const long long int inf = 1e18;
const long long int mod = 998244353;
bool sortbysec(const pair<long long int, long long int> &a,
               const pair<long long int, long long int> &b) {
  return (a.second < b.second);
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL), cout.tie(NULL);
  long long int t, i, j, n, m, curr, p, x, mini = inf;
  long long int prime[100070] = {0};
  prime[0] = prime[1] = 1;
  for (i = 2; i * i < 100070; i++) {
    if (prime[i] != 1) {
      for (j = i * i; j < 100070; j += i) prime[j] = 1;
    }
  }
  i = 100069;
  while (prime[i] != 0) i++;
  curr = i;
  while (i >= 0) {
    if (!prime[i]) curr = i;
    prime[i] = curr;
    i--;
  }
  cin >> n >> m;
  long long int col[m], row[n];
  for (long long int i = 0; i < n; i++) row[i] = 0;
  for (long long int i = 0; i < m; i++) col[i] = 0;
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> p;
      x = prime[p] - p;
      col[j] += x;
      row[i] += x;
    }
    mini = min(mini, row[i]);
  }
  for (i = 0; i < m; i++) mini = min(mini, col[i]);
  cout << mini << endl;
}
