#include <bits/stdc++.h>
using namespace std;
vector<long long int> a(900005, 1);
vector<long long int> v;
void sieve(long long int nn) {
  for (long long int i = 2; i < nn; i++) {
    if (a[i]) {
      v.push_back(i);
      for (long long int j = 2; j * i < nn; j++) a[i * j] = 0;
    }
  }
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  a[1] = 0;
  sieve(200005);
  long long int n, m;
  cin >> n >> m;
  vector<vector<long long int>> ma(n, vector<long long int>(m));
  for (long long int i = 0; i < n; i++) {
    for (long long int j = 0; j < m; j++) {
      cin >> ma[i][j];
    }
  }
  long long int s = 0, mn = INT_MAX;
  for (long long int i = 0; i < n; i++) {
    s = 0;
    for (long long int j = 0; j < m; j++) {
      s += (*lower_bound(v.begin(), v.end(), ma[i][j])) - ma[i][j];
    }
    mn = min(mn, s);
  }
  for (long long int j = 0; j < m; j++) {
    s = 0;
    for (long long int i = 0; i < n; i++) {
      s += (*lower_bound(v.begin(), v.end(), ma[i][j])) - ma[i][j];
    }
    mn = min(mn, s);
  }
  cout << mn;
}
