#include <bits/stdc++.h>
using namespace std;
const long long maxn = 2e5 + 10;
long long N, M, vis[maxn], primes[maxn], tot = 0, arr[505][505];
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> N >> M;
  for (register long long i = 1; i <= N; ++i) {
    for (register long long j = 1; j <= M; ++j) {
      cin >> arr[i][j];
    }
  }
  for (register long long i = 2; i < maxn; ++i) {
    if (vis[i]) continue;
    primes[++tot] = i;
    for (register long long j = i * i; j < maxn; j += i) {
      vis[j] = true;
    }
  }
  long long ans = 1e18;
  for (register long long i = 1; i <= N; ++i) {
    long long tmp = 0;
    for (register long long j = 1; j <= M; ++j) {
      auto it = lower_bound(primes + 1, primes + 1 + tot, arr[i][j]);
      tmp += *it - arr[i][j];
    }
    ans = min(ans, tmp);
  }
  for (register long long j = 1; j <= M; ++j) {
    long long tmp = 0;
    for (register long long i = 1; i <= N; ++i) {
      auto it = lower_bound(primes + 1, primes + 1 + tot, arr[i][j]);
      tmp += *it - arr[i][j];
    }
    ans = min(ans, tmp);
  }
  cout << ans << endl;
  return 0;
}
