#include <bits/stdc++.h>
using namespace std;
vector<long long int> v(1000000 + 1, 0);
void sieve() {
  long long int a;
  bool prime[1000000 + 1];
  memset(prime, true, sizeof(prime));
  prime[0] = prime[1] = false;
  for (long long int i = 2; i * i <= 1000000; i++) {
    if (prime[i]) {
      for (long long int j = (i * i); j <= 1000000; j += i) {
        prime[j] = false;
      }
    }
  }
  for (long long int i = 1000000; i >= 1; i--) {
    if (prime[i])
      a = i;
    else
      v[i] = a - i;
  }
}
int main() {
  long long int a, b, c, d, i, j, k, l, m, n, p, q, r, u, w, e, f, g, h, t,
      ct = 0, ct1 = 0, ct2 = 0, ck = 0, ck1 = 0, ck2 = 0, ln, ln1, start, end,
      mid;
  long long int a1 = 0, a2 = 0, a3 = 0, a4 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0,
                sum = 0, sum1 = 0, max1, max2, min1, min2;
  double x, y, z;
  char ch, ch1, ch2;
  ios ::sync_with_stdio(false);
  cin.tie(0);
  ;
  sieve();
  cin >> n >> m;
  vector<long long int> v1[n];
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> a;
      v1[i].push_back(v[a]);
    }
  }
  min1 = 1000000000000000005;
  for (i = 0; i < n; i++) {
    sum = 0;
    for (j = 0; j < m; j++) {
      sum += v1[i][j];
    }
    min1 = min(min1, sum);
  }
  for (j = 0; j < m; j++) {
    sum = 0;
    for (i = 0; i < n; i++) {
      sum += v1[i][j];
    }
    min1 = min(min1, sum);
  }
  cout << min1 << endl;
  return 0;
}
