#include <bits/stdc++.h>
using namespace std;
long long count(int n) {
  if (n == 1)
    return 0;
  else if (n == 3)
    return 8;
  else
    return count(n - 2) + (n * 4 - 4) * floor(n / 2.0);
}
bool isPrime(int n) {
  int i, flag = 0;
  if (n % 2 == 0)
    flag = 1;
  else {
    for (i = 3; i <= sqrt(n); i += 2) {
      if (n % i == 0) {
        flag = 1;
        break;
      }
    }
  }
  if (flag == 1)
    return false;
  else
    return true;
}
int next_prime(int a) {
  int i, j, flag;
  for (i = a + 1;; i++) {
    flag = 0;
    if (i % 2 != 0) {
      for (j = 3; j <= sqrt(i); j++) {
        if (i % j == 0) flag = 1;
      }
    }
    if (flag == 0 && i % 2 != 0) return i;
  }
}
int main() {
  long long t, tt, n, d, max, min, flag, c, l, k, i, j, m, x, start, end;
  t = 1;
  while (t--) {
    cin >> n >> m;
    int a[n][m];
    vector<int> v;
    max = -1;
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        cin >> a[i][j];
        if (a[i][j] > max) max = a[i][j];
      }
    }
    start = -1;
    tt = next_prime(max);
    bool prime[tt + 1];
    memset(prime, true, sizeof(prime));
    for (int p = 2; p * p <= tt; p++) {
      if (prime[p] == true) {
        for (int i = p * 2; i <= tt; i += p) prime[i] = false;
      }
    }
    for (i = 0; i < n; i++) {
      c = 0;
      for (j = 0; j < m; j++) {
        if (a[i][j] == 1)
          c = c + 1;
        else if (prime[a[i][j]] == true)
          c = c;
        else {
          for (k = a[i][j]; prime[k] == false; k++) {
          }
          c = c + k - a[i][j];
        }
      }
      v.push_back(c);
    }
    for (j = 0; j < m; j++) {
      c = 0;
      for (i = 0; i < n; i++) {
        if (a[i][j] == 1)
          c = c + 1;
        else if (prime[a[i][j]] == true)
          c = c;
        else {
          for (k = a[i][j]; prime[k] == false; k++) {
          }
          c = c + k - a[i][j];
        }
      }
      v.push_back(c);
    }
    sort(v.begin(), v.end());
    cout << v[0] << endl;
  }
}
