#include <bits/stdc++.h>
using namespace std;
int main() {
  int t, i, j;
  bool isprime[100005];
  memset(isprime, true, sizeof(isprime));
  for (i = 2; i * i <= 100003; i++) {
    if (isprime[i] == true) {
      for (j = i * i; j < 100005; j += i) {
        isprime[j] = 0;
      }
    }
  }
  int nprime[100005];
  for (i = 100003; i >= 1; i--) {
    if (isprime[i] == true) {
      nprime[i] = i;
      t = i;
    } else
      nprime[i] = t;
  }
  nprime[1] = 2;
  int n, m;
  cin >> n >> m;
  long long a[n][m];
  long long _, minro = 111111, minco = 111111, sum = 0;
  for (i = 0; i < n; i++) {
    sum = 0;
    for (j = 0; j < m; j++) {
      cin >> _;
      a[i][j] = (nprime[_] - _);
      sum += (a[i][j]);
    }
    if (sum < minro) minro = sum;
  }
  for (i = 0; i < m; i++) {
    sum = 0;
    for (j = 0; j < n; j++) {
      sum += a[j][i];
    }
    if (minco > sum) minco = sum;
  }
  int ans = (minro > minco) ? minco : minro;
  cout << ans << "\n";
  return 0;
}
