#include <bits/stdc++.h>
using namespace std;
const int N = 510;
const int M = 100100;
int prime[M + 10], a[N][N], b[N][N], n, m;
int main() {
  prime[1] = 1;
  for (int i = 2; i <= M; ++i)
    if (prime[i] == 0)
      for (int j = i + i; j <= M; j += i) prime[j] = 1;
  cin >> n >> m;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) cin >> a[i][j];
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      while (prime[a[i][j] + b[i][j]]) ++b[i][j];
  int mn = 1 << 30;
  for (int i = 1; i <= n; ++i) {
    int s = 0;
    for (int j = 1; j <= m; ++j) s += b[i][j];
    mn = min(mn, s);
  }
  for (int j = 1; j <= m; ++j) {
    int s = 0;
    for (int i = 1; i <= n; ++i) s += b[i][j];
    mn = min(mn, s);
  }
  cout << mn << '\n';
}
