#include <bits/stdc++.h>
using namespace std;
vector<int> primes;
int sieveCountPrimesInRange(long long n) {
  vector<bool> isPrime(n + 1, true);
  int cnt = 0;
  isPrime[0] = isPrime[1] = 0;
  for (long long i = 1; i <= (n / i); i++) {
    if (isPrime[i])
      for (long long j = i * 2; j <= n; j += i) isPrime[j] = 0;
  }
  for (int i = 0; i < isPrime.size(); i++) {
    isPrime[i] ? cnt++ : cnt;
    if (isPrime[i]) primes.push_back(i);
  }
  return cnt;
}
int P[500][500];
int main() {
  int n, m, c = 0;
  cin >> n >> m;
  vector<int>::iterator it;
  vector<int> v;
  sieveCountPrimesInRange(100000 + 200);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> P[i][j];
    }
  }
  for (int i = 0; i < n; i++) {
    c = 0;
    for (int j = 0; j < m; j++) {
      it = lower_bound(primes.begin(), primes.end(), P[i][j]);
      c += *it - P[i][j];
    }
    v.push_back(c);
  }
  for (int i = 0; i < m; i++) {
    c = 0;
    for (int j = 0; j < n; j++) {
      it = lower_bound(primes.begin(), primes.end(), P[j][i]);
      c += *it - P[j][i];
    }
    v.push_back(c);
  }
  cout << *(min_element(v.begin(), v.end())) << endl;
}
