#include <bits/stdc++.h>
using namespace std;
const int N = 1000001;
bool crib[N];
void criba() {
  memset(crib, true, sizeof(crib));
  crib[1] = false;
  for (int i = 2; i <= N / 2; i++) {
    if (crib[i] == true) {
      for (int j = 2 * i; j <= N; j += i) {
        crib[j] = false;
      }
    }
  }
}
int mov_fila(int A[500][500], int i, int m) {
  int sum = 0;
  for (int j = 0; j < m; j++) {
    if (crib[A[i][j]] == false) {
      for (int k = A[i][j] + 1; k <= N; k++) {
        if (crib[k]) {
          sum += k - A[i][j];
          break;
        }
      }
    }
  }
  return sum;
}
int mov_columna(int A[][500], int j, int n) {
  int sum = 0;
  for (int i = 0; i < n; i++) {
    if (crib[A[i][j]] == false) {
      for (int k = A[i][j] + 1; k <= N; k++) {
        if (crib[k]) {
          sum += k - A[i][j];
          break;
        }
      }
    }
  }
  return sum;
}
int main() {
  int n, m;
  cin >> n;
  cin >> m;
  int A[n][500];
  criba();
  int min;
  bool termina = false;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> A[i][j];
    }
    if (i == 0) {
      min = mov_fila(A, i, m);
    } else {
      if (mov_fila(A, i, m) < min) min = mov_fila(A, i, m);
    }
    if (min == 0) {
      cout << "0";
      termina = true;
      break;
    }
  }
  if (!termina) {
    for (int j = 0; j < m; j++) {
      if (mov_columna(A, j, n) < min) min = mov_columna(A, j, n);
      if (min == 0) {
        cout << "0";
        termina = true;
        break;
      }
    }
  }
  if (!termina) cout << min;
  return 0;
}
