#include <bits/stdc++.h>
using namespace std;
int a[600][600];
bool isprime(int x) {
  if (x == 1) return 0;
  if (x == 2) return 1;
  for (int i = 2; i * i <= x; i++) {
    if (x % i == 0) return 0;
  }
  return 1;
}
int v[600], h[600];
bool pr[100007];
vector<int> prr;
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  pr[1] = 0;
  pr[2] = 1;
  for (int i = 2; i < 100007; i++) pr[i] = 1;
  for (int i = 2; i < 100007; i++) {
    if (pr[i]) {
      prr.push_back(i);
      for (int j = i + i; j < 100007; j += i) pr[j] = 0;
    }
  }
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int x = 0;
      if (!isprime(a[i][j]))
        x = *upper_bound(prr.begin(), prr.end(), a[i][j]);
      else
        x = a[i][j];
      if (isprime(x)) {
        v[i] += x - a[i][j];
        h[j] += x - a[i][j];
      }
    }
  int min = 1000000000;
  for (int i = 0; i < n; i++)
    if (v[i] < min) min = v[i];
  for (int i = 0; i < m; i++)
    if (h[i] < min) min = h[i];
  cout << min;
  cin >> min;
}
