#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, h, i, j, t, m, l, r, q;
  long long p = 0, k, w, z, x, y, d, p1, h1;
  string s = "", st = "", s1 = "", s2 = "";
  q = 1;
  for (l = 0; l < q; l++) {
    std::cin >> n >> m;
    int a[n][m];
    for (i = 0; i < n; i++)
      for (j = 0; j < m; j++) cin >> a[i][j];
    std::set<int> primes;
    int is_prime[100005] = {0};
    for (i = 2; i < 100005; i++) {
      if (is_prime[i] == 0) {
        primes.insert(i);
        for (j = i * i; j < 100005; j += i) is_prime[j] = 1;
      }
    }
    k = 4000009;
    for (i = 0; i < n; i++) {
      x = 0;
      for (j = 0; j < m; j++) {
        p = a[i][j];
        while (primes.count(p) == 0) {
          p++;
          x++;
        }
      }
      k = min(k, x);
    }
    for (j = 0; j < m; j++) {
      x = 0;
      for (i = 0; i < n; i++) {
        p = a[i][j];
        while (primes.count(p) == 0) {
          p++;
          x++;
        }
      }
      k = min(k, x);
    }
    std::cout << k << std::endl;
  }
  return 0;
}
