#include <bits/stdc++.h>
using namespace std;
string uppercase(string s) {
  transform(s.begin(), s.end(), s.begin(), ::toupper);
  return s;
}
string lowercase(string s) {
  transform(s.begin(), s.end(), s.begin(), ::tolower);
  return s;
}
set<pair<int, pair<string, int>>> sp;
vector<vector<int>> v2d(5, vector<int>(5, 7));
vector<int> v;
void Isprime() {
  for (int i = 2; i <= 100010; i++) {
    int ptr = 1;
    for (int j = 2; j * j <= i; ++j) {
      if (i % j == 0) {
        ptr = 0;
        break;
      }
    }
    if (ptr) v.push_back(i);
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  Isprime();
  int n, m;
  cin >> n >> m;
  int A[505][505];
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> A[i][j];
    }
  }
  int ans = 0, mn = 1e7;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      int p = lower_bound(v.begin(), v.end(), A[i][j]) - v.begin();
      ans += (v[p] - A[i][j]);
    }
    mn = min(ans, mn);
    ans = 0;
  }
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
      int p = lower_bound(v.begin(), v.end(), A[j][i]) - v.begin();
      ans += (v[p] - A[j][i]);
    }
    mn = min(ans, mn);
    ans = 0;
  }
  cout << mn << "\n";
  return 0;
}
