#include <bits/stdc++.h>
using namespace std;
set<long long> SieveOfEratosthenes(int n) {
  bool prime[n + 1];
  set<long long> pr;
  memset(prime, true, sizeof(prime));
  for (long long p = 2; p <= n; p++) {
    if (prime[p] == true) {
      pr.insert(p);
      for (long long i = p * p; i <= n; i += p) prime[i] = false;
    }
  }
  return pr;
}
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
label:
  int n, m;
  cin >> n >> m;
  long long a[n][m];
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) cin >> a[i][j];
  set<long long> pr;
  pr = SieveOfEratosthenes(200000);
  set<long long>::iterator it;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      it = pr.lower_bound(a[i][j]);
      a[i][j] = *it - a[i][j];
    }
  }
  long long ans = 1000000000000;
  for (int i = 0; i < n; i++) {
    long long sum = 0;
    for (int j = 0; j < m; j++) {
      sum += a[i][j];
    }
    ans = min(ans, sum);
  }
  for (int i = 0; i < m; i++) {
    long long sum = 0;
    for (int j = 0; j < n; j++) {
      sum += a[j][i];
    }
    ans = min(ans, sum);
  }
  cout << ans;
  return 0;
}
