#include <bits/stdc++.h>
using namespace std;
struct hash_pair {
  template <class T1, class T2>
  size_t operator()(const pair<T1, T2>& p) const {
    auto hash1 = hash<T1>{}(p.first);
    auto hash2 = hash<T2>{}(p.second);
    return hash1 ^ hash2;
  }
};
long long t;
vector<long long> v;
long long arr[1000005];
void seive() {
  long long a, b, c, d, i, j;
  for (i = 1; i <= 1e6; i++) {
    arr[i] = i;
    if (i % 2 == 0) arr[i] = 2;
  }
  for (i = 3; i * i < 1e6; i += 2) {
    if (arr[i] != i) continue;
    for (j = i * i; j <= 1e6; j += 2 * i) {
      if (arr[j] == j) arr[j] = i;
    }
  }
  for (i = 2; i <= 1e6; i++) {
    if (arr[i] == i) v.push_back(i);
  }
}
long long prime[505][505];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long a, b, c, d, e, f, g, i, j;
  long long n, k;
  seive();
  cin >> a >> b;
  for (i = 1; i <= a; i++) {
    for (j = 1; j <= b; j++) {
      cin >> d;
      f = lower_bound(v.begin(), v.end(), d) - v.begin();
      prime[i][j] = v[f] - d;
    }
  }
  f = 0x3f3f3f3f;
  for (i = 1; i <= a; i++) {
    g = 0;
    for (j = 1; j <= b; j++) {
      g += prime[i][j];
    }
    f = min(g, f);
  }
  for (i = 1; i <= b; i++) {
    g = 0;
    for (j = 1; j <= a; j++) {
      g += prime[j][i];
    }
    f = min(g, f);
  }
  cout << f << endl;
  return 0;
}
