#include <bits/stdc++.h>
using namespace std;
long long k, p, h, b[555][555], a[555555];
long long mid, n, o, r, l;
bool y, m[1000001];
void s(long long r) {
  for (long long i = 2; i * i <= r; i++) {
    if (m[i] == false) {
      for (long long j = i * 2; j <= r; j += i) {
        m[j] = true;
      }
    }
  }
  for (long long i = 2; i <= r; i++) {
    if (m[i] == false) a[o++] = i;
  }
}
int main() {
  s(1000000);
  p = o = h = 1e15;
  cin >> n >> o;
  for (long long i = 0; i < n; i++) {
    for (int j = 0; j < o; j++) cin >> b[i][j];
  }
  for (long long i = 0; i < n; i++) {
    k = 0;
    long long u = 0;
    for (long long j = 0; j < o; j++) {
      r = 78450;
      l = 0;
      k = 1e15;
      while (l <= r) {
        mid = (l + r) / 2;
        if (b[i][j] > a[mid]) {
          l = mid + 1;
        } else if (b[i][j] < a[mid]) {
          k = min(k, a[mid] - b[i][j]);
          r = mid - 1;
        } else {
          k = 0;
          break;
        }
      }
      u += k;
    }
    p = min(u, p);
  }
  for (long long j = 0; j < o; j++) {
    k = 0;
    long long u = 0;
    for (long long i = 0; i < n; i++) {
      r = 78450;
      l = 0;
      k = 1e15;
      while (l <= r) {
        mid = (l + r) / 2;
        if (b[i][j] > a[mid]) {
          l = mid + 1;
        } else if (b[i][j] < a[mid]) {
          k = min(k, a[mid] - b[i][j]);
          r = mid - 1;
        } else {
          k = 0;
          break;
        }
      }
      u += k;
    }
    h = min(u, h);
  }
  cout << min(h, p);
}
