#include <bits/stdc++.h>
using namespace std;
const int oo = INT_MAX;
int arr[1000000];
vector<int> p;
void sieve() {
  arr[0] = arr[1] = 1;
  for (int i = 2; i < 1000000; ++i) {
    if (!arr[i]) {
      p.push_back(i);
      for (long long j = i; j * i < 1000000; ++j) {
        arr[i * j] = 1;
      }
    }
  }
}
int main() {
  sieve();
  int n, m, x;
  scanf("%d%d", &n, &m);
  int a[n][m];
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      scanf("%d", &x);
      a[i][j] = p[lower_bound(p.begin(), p.end(), x) - p.begin()] - x;
    }
  }
  int mi = oo, s;
  for (int i = 0; i < n; ++i) {
    s = 0;
    for (int j = 0; j < m; ++j) {
      s += a[i][j];
    }
    mi = min(mi, s);
  }
  for (int i = 0; i < m; ++i) {
    s = 0;
    for (int j = 0; j < n; ++j) {
      s += a[j][i];
    }
    mi = min(mi, s);
  }
  cout << mi;
}
