#include <bits/stdc++.h>
using namespace std;
priority_queue<int, vector<int>, greater<int> > Q;
const int INF = 1e9 + 9;
long int pow(long int a, long int b, int m) {
  a %= m;
  long long res = 1;
  while (b > 0) {
    if (b & 1) res = res * a % m;
    a = a * a % m;
    b >>= 1;
  }
  return res;
}
vector<int> ans(100051);
vector<bool> prime(100051, true);
void seive(int n) {
  prime[1] = false;
  prime[0] = false;
  for (int p = 2; p * p <= n; p++) {
    if (prime[p] == true) {
      for (int i = p * p; i <= n; i += p) prime[i] = false;
    }
  }
  long long pre = 100051;
  for (long long i = n - 1; i >= 1; i--) {
    if (prime[i])
      pre = i;
    else
      ans[i] = pre;
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  seive(100050);
  int n, m;
  cin >> n >> m;
  int arr[n][m];
  vector<int> sumr(n, 0), sumc(m, 0);
  int moves = INT_MAX;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> arr[i][j];
      if (!prime[arr[i][j]]) {
        sumr[i] += ans[arr[i][j]] - arr[i][j];
        sumc[j] += ans[arr[i][j]] - arr[i][j];
      }
    }
    moves = min(moves, sumr[i]);
  }
  for (int i = 0; i < m; i++) {
    moves = min(moves, sumc[i]);
  }
  cout << moves << endl;
}
