#include <bits/stdc++.h>
using namespace std;
const double PI = atan(1) * 4;
const int mod = 1e9 + 7;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int tt = 1;
  while (tt--) {
    int sieve[100010];
    for (int i = int(0); i < int((100010) + 1); ++i) sieve[i] = i;
    set<int> st;
    for (int i = int(2); i < int((100010) + 1); ++i) {
      if (sieve[i] == i) {
        for (int j = int(i); j < int((100010) + 1); ++j) {
          if (sieve[j] == j) sieve[j] = i;
          j += i - 1;
        }
      }
    }
    for (int i = int(2); i < int((100010) + 1); ++i)
      if (sieve[i] == i) st.insert(i);
    int n, m;
    cin >> n >> m;
    int a[n][m];
    for (int i = int(0); i < int(n); ++i) {
      for (int j = int(0); j < int(m); ++j) {
        cin >> a[i][j];
      }
    }
    long long ans = 1e18;
    for (int i = int(0); i < int(n); ++i) {
      long long sum = 0;
      for (int j = int(0); j < int(m); ++j) {
        int k = *st.lower_bound(a[i][j]);
        sum += k - a[i][j];
      }
      ans = min(ans, sum);
    }
    for (int j = int(0); j < int(m); ++j) {
      long long sum = 0;
      for (int i = int(0); i < int(n); ++i) {
        int k = *st.lower_bound(a[i][j]);
        sum += k - a[i][j];
      }
      ans = min(ans, sum);
    }
    cout << ans;
  }
  cerr << "Time elapsed : " << 1.0 * clock() / CLOCKS_PER_SEC << " sec \n";
  return 0;
}
