#include <bits/stdc++.h>
using namespace std;
vector<long long int> prime;
bool arr[100009];
void sieve() {
  long long int k = sqrt(100009);
  for (int i = 3; i <= k; i += 2) {
    if (arr[i] == 0) {
      for (long long int j = i * i; j < 100009; j += 2 * i) {
        arr[j] = 1;
      }
    }
  }
  arr[1] = 1;
  for (long long int i = 4; i < 100009; i += 2) {
    arr[i] = 1;
  }
}
int main() {
  sieve();
  long long int n, m, matrix[501][501], temp, count, primecount, lowest;
  while (cin >> n >> m) {
    lowest = 999999999;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        scanf("%lld", &matrix[i][j]);
      }
    }
    for (int i = 0; i < n; i++) {
      count = primecount = 0;
      for (int j = 0; j < m; j++) {
        temp = matrix[i][j];
        if (arr[temp] == 0) {
          primecount++;
        } else {
          for (int k = temp + 1;; k++) {
            count++;
            if (arr[k] == 0) break;
          }
        }
      }
      if (primecount == m)
        lowest = 0;
      else if (lowest > count)
        lowest = count;
    }
    for (int i = 0; i < m; i++) {
      count = primecount = 0;
      for (int j = 0; j < n; j++) {
        temp = matrix[j][i];
        if (arr[temp] == 0) {
          primecount++;
        } else {
          for (int k = temp + 1;; k++) {
            count++;
            if (arr[k] == 0) break;
          }
        }
      }
      if (primecount == n)
        lowest = 0;
      else if (lowest > count)
        lowest = count;
    }
    cout << lowest << endl;
  }
  return 0;
}
