#include <bits/stdc++.h>
using namespace std;
const int inf = 0x7FFFFFFF;
const double eps = 1e-9L;
const double pi = acos(-1.0);
using namespace std;
int prime[100100 + 10], pf[100100 + 10];
int row[520], col[520], con[100100 + 5];
void make() {
  int count = 0;
  prime[count++] = 2;
  for (int i = 3; i < 100100; i += 2) {
    if (pf[i] == 0) {
      prime[count++] = i;
      for (int j = i; j < 100100; j += i) {
        pf[j] = 1;
      }
    }
  }
  count = 0;
  for (int i = 0; i <= 100000 + 3; i++) {
    if (prime[count] < i) count++;
    con[i] = prime[count] - i;
  }
}
int main() {
  make();
  int n, m;
  cin >> n >> m;
  int mn = inf;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int a;
      cin >> a;
      col[i] += con[a];
      row[j] += con[a];
    }
  for (int i = 0; i < n; i++) mn = min(mn, col[i]);
  for (int j = 0; j < m; j++) mn = min(mn, row[j]);
  cout << mn << endl;
  return 0;
}
