#include <bits/stdc++.h>
using namespace std;
int matrix[505][505];
int m, n;
int col[505];
int row[505];
int prime[110000];
int pc;
bool visit[110000];
void init() {
  for (int i = 2; i < 110000; i++) {
    if (visit[i]) continue;
    for (int j = i * 2; j < 110000; j += i) visit[j] = true;
  }
  for (int i = 2; i < 110000; i++)
    if (!visit[i]) prime[pc++] = i;
}
int next(int num) {
  int l, r, mid;
  l = 0;
  r = pc - 1;
  while (l < r) {
    mid = (l + r) / 2;
    if (prime[mid] < num)
      l = mid + 1;
    else
      r = mid;
  }
  return prime[r] - num;
}
int main() {
  int i, j, v, tmp, min;
  cin >> n >> m;
  init();
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++) cin >> matrix[i][j];
  for (i = 0; i < n; i++) {
    v = 0;
    for (j = 0; j < m; j++) {
      tmp = next(matrix[i][j]);
      col[j] += tmp;
      v += tmp;
    }
    row[i] = v;
  }
  min = INT_MAX;
  for (i = 0; i < n; i++)
    if (min > row[i]) min = row[i];
  for (j = 0; j < m; j++)
    if (min > col[j]) min = col[j];
  cout << min << endl;
  return 0;
}
