#include <bits/stdc++.h>
using namespace std;
int main() {
  long long is[110005];
  for (long long i = 2; i < 110005; i++) {
    if (is[i] == 0) {
      for (long long j = i * i; j < 110005; j += i) {
        is[j] = 1;
      }
    }
  }
  long long x;
  map<long long, long long> p;
  is[1] = 1;
  for (long long i = 110004; i >= 0; i--) {
    if (is[i] == 0) {
      x = i;
    }
    p[i] = x - i;
  }
  long long n, m;
  cin >> n >> m;
  long long a[n][m];
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  long long mi = 1000000007;
  for (long long i = 0; i < n; i++) {
    long long leo = 0;
    for (long long j = 0; j < m; j++) {
      long long x = a[i][j];
      leo += p[x];
    }
    mi = min(mi, leo);
  }
  for (long long i = 0; i < m; i++) {
    long long leo = 0;
    for (long long j = 0; j < n; j++) {
      long long x = a[j][i];
      leo += p[x];
    }
    mi = min(mi, leo);
  }
  cout << mi << "\n";
  return 0;
}
