#include <bits/stdc++.h>
using namespace std;
int prime[100001];
int binsearch(int key, int imin, int imax) {
  if (imax < imin)
    return prime[imin];
  else {
    int imid = (imin + imax) / 2;
    if (prime[imid] > key)
      return binsearch(key, imin, imid - 1);
    else if (prime[imid] < key)
      return binsearch(key, imid + 1, imax);
    else
      return key;
  }
}
int main() {
  int x = 110001;
  bool a[x];
  for (int i = 0; i < x; i++) a[i] = 1;
  a[0] = 0;
  a[1] = 0;
  int start;
  start = 2;
  while ((start * start) < x) {
    for (int i = start * start; i < x; i = i + start) a[i] = 0;
    for (int i = start + 1; i < x; i++) {
      if (a[i]) {
        start = i;
        break;
      }
    }
  }
  int k = 0;
  for (int i = 0; i < x; i++) {
    if (a[i] == 1) {
      prime[k] = i;
      k++;
    }
  }
  int n, m;
  scanf("%d%d", &n, &m);
  int arr[n][m];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) scanf("%d", &arr[i][j]);
  }
  long long ans = LLONG_MAX;
  for (int i = 0; i < n; i++) {
    int temp = 0;
    for (int j = 0; j < m; j++) {
      temp += binsearch(arr[i][j], 0, k - 1) - arr[i][j];
    }
    if (ans > temp) ans = temp;
  }
  for (int j = 0; j < m; j++) {
    int temp = 0;
    for (int i = 0; i < n; i++) {
      temp += binsearch(arr[i][j], 0, k - 1) - arr[i][j];
    }
    if (ans > temp) ans = temp;
  }
  cout << ans;
  return 0;
}
