#include <bits/stdc++.h>
using namespace std;
bool arr[1000000 + 100];
void findPrime(int size) {
  memset(arr, true, sizeof(arr));
  arr[0] = false;
  arr[1] = false;
  for (int i = 2; i <= size; i++)
    if (arr[i])
      for (int j = i + i; j <= size; j += i) arr[j] = false;
}
int main() {
  int n, m;
  while (cin >> n >> m) {
    int max = 0;
    int a[505][505], b[505][505];
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
        if (a[i][j] > max) max = a[i][j];
      }
    findPrime(max + 100);
    int h[505], z[505];
    memset(h, 0, sizeof(h));
    memset(z, 0, sizeof(z));
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) {
        while (!arr[a[i][j]++]) {
          h[i]++;
          z[j]++;
        }
      }
    int ans = 1 << 30;
    for (int i = 0; i < n; i++) {
      if (h[i] < ans) ans = h[i];
    }
    for (int i = 0; i < m; i++) {
      if (z[i] < ans) ans = z[i];
    }
    cout << ans << endl;
  }
}
