#include <bits/stdc++.h>
using namespace std;
vector<int> arr(78498);
vector<vector<int>> in(505, vector<int>(505));
vector<vector<int>> out(505, vector<int>(505));
void SieveOfEratosthenes(int n) {
  vector<bool> prime(n + 1, true);
  for (int p = 2; p * p <= n; p++) {
    if (prime[p] == true) {
      for (int i = p * p; i <= n; i += p) prime[i] = false;
    }
  }
  int i = 0;
  for (int p = 2; p <= n; p++)
    if (prime[p]) arr[i++] = p;
}
int f(int val) {
  int l = 0, u = arr.size() - 1, res = -1;
  while (l <= u) {
    int mid = (l + u) / 2;
    if (val == arr[mid])
      return -2;
    else if (val < arr[mid]) {
      res = mid;
      u = mid - 1;
    } else
      l = mid + 1;
  }
  return res;
}
int main() {
  SieveOfEratosthenes(1000000);
  sort(arr.begin(), arr.end());
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) cin >> in[i][j];
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int res = f(in[i][j]);
      if (res == -2)
        out[i][j] = 0;
      else if (res == -1)
        cout << "error" << endl;
      else {
        out[i][j] = arr[res] - in[i][j];
      }
    }
  }
  long long mini = pow(10, 18);
  for (int i = 0; i < n; i++) {
    long long tot = 0;
    for (int j = 0; j < m; j++) tot += (long long)out[i][j];
    mini = min(mini, tot);
  }
  for (int j = 0; j < m; j++) {
    long long tot = 0;
    for (int i = 0; i < n; i++) tot += (long long)out[i][j];
    mini = min(mini, tot);
  }
  cout << mini << endl;
}
