#include <bits/stdc++.h>
using namespace std;
const int LIMIT = 1000005;
int sieve[LIMIT + 1];
int primes[LIMIT + 1];
int mark_primes() {
  int primeCount = 1;
  for (int i = 0; i <= LIMIT; ++i) sieve[i] = 0;
  for (int i = 2; i <= LIMIT; ++i) {
    if (!sieve[i]) {
      primes[primeCount] = i;
      sieve[i] = primeCount;
      primeCount++;
    }
    for (int j = 1; j <= sieve[i] && i * primes[j] <= LIMIT; j++) {
      sieve[i * primes[j]] = j;
    }
  }
  return primeCount;
}
const int MAXN = 505;
int a[MAXN][MAXN];
int main() {
  int k = mark_primes();
  int n, m;
  while (cin >> n >> m) {
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> a[i][j];
      }
    }
    int best_row = INT_MAX;
    for (int i = 0; i < n; ++i) {
      int count = 0;
      for (int j = 0; j < m; ++j) {
        int next_prime = *(lower_bound(primes, primes + k, a[i][j]));
        count += next_prime - a[i][j];
      }
      best_row = min(best_row, count);
    }
    int best_col = INT_MAX;
    for (int j = 0; j < m; ++j) {
      int count = 0;
      for (int i = 0; i < n; ++i) {
        int next_prime = *(lower_bound(primes, primes + k, a[i][j]));
        count += next_prime - a[i][j];
      }
      best_col = min(best_col, count);
    }
    cout << min(best_row, best_col) << endl;
  }
  return 0;
}
