#include <bits/stdc++.h>
using namespace std;
int a[505][505];
bool isprime[100005];
int prime[100005], x = 0;
int bse(int temp) {
  int beg = 0, last = x - 1, an = 10000000000;
  while (beg <= last) {
    int mid = beg + (last - beg) / 2;
    if (prime[mid] == temp)
      return prime[mid];
    else if (prime[mid] > temp) {
      an = min(an, prime[mid]);
      last = mid - 1;
    } else
      beg = mid + 1;
  }
  return an;
}
int main() {
  int i, j, temp = 0, ans = 10000000000, n, m;
  for (i = 2; i <= 100005; i++) {
    if (!isprime[i]) {
      prime[x++] = i;
      for (j = 2; j * i <= 100005; j++) isprime[i * j] = true;
    }
  }
  cin >> n >> m;
  for (i = 0; i < n; i++) {
    temp = 0;
    for (j = 0; j < m; j++) {
      cin >> a[i][j];
      temp += bse(a[i][j]) - a[i][j];
    }
    ans = min(ans, temp);
  }
  for (i = 0; i < m; i++) {
    temp = 0;
    for (j = 0; j < n; j++) {
      temp += bse(a[j][i]) - a[j][i];
    }
    ans = min(ans, temp);
  }
  cout << ans << endl;
  return 0;
}
