#include <bits/stdc++.h>
using namespace std;
void fast_in_out() {
  std::ios_base::sync_with_stdio(NULL);
  cin.tie(NULL);
  cout.tie(NULL);
}
int dx[] = {0, 0, -1, 1, -1, 1, -1, 1, 0};
int dy[] = {-1, 1, 0, 0, -1, -1, 1, 1, 0};
int lx[] = {2, 2, -1, 1, -2, -2, -1, 1};
int ly[] = {-1, 1, 2, 2, 1, -1, -2, -2};
const long double eps = 1e-9;
const int N = 1e5 + 50, M = 1e5 + 10, mod = 1e9 + 7;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long lcm(long long a, long long b) {
  long long t = gcd(a, b);
  return t ? (a / t * b) : 0;
}
bool prm[N];
vector<int> v;
int cost[N];
int adj[505][505];
long long row[505], col[505];
void sieve() {
  v.push_back(2);
  for (int i = 4; i < N; i += 2) prm[i] = 1;
  for (int i = 3; i < N; i += 2)
    if (!prm[i]) {
      v.push_back(i);
      for (int j = i + i; j < N; j += i) prm[j] = 1;
    }
}
int main() {
  fast_in_out();
  sieve();
  int n, m;
  cin >> n >> m;
  for (int i = 0, j = 0; i < M; i++) {
    cost[i] = v[j] - i;
    if (v[j] == i) ++j;
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int x;
      cin >> x;
      x = cost[x];
      row[i] += x;
      col[j] += x;
    }
  }
  long long ans = row[0];
  for (int i = 0; i < n; i++) ans = min(ans, row[i]);
  for (int j = 0; j < m; j++) ans = min(ans, col[j]);
  cout << ans << '\n';
  return 0;
}
