#include <bits/stdc++.h>
const long double eps = 1e-12;
using namespace std;
vector<long long int> primes;
long long int p[1000001];
void primeSeive() {
  long long int n = 1000001;
  p[0] = p[1] = 0;
  p[2] = 1;
  for (long long int i = 3; i <= n; i += 2) {
    p[i] = 1;
  }
  for (long long int i = 3; i <= n; i += 2) {
    if (p[i] == 1) {
      for (long long int j = i * i; j <= n; j = j + i) {
        p[j] = 0;
      }
    }
  }
  primes.push_back(2);
  for (long long int i = 3; i <= n; i += 2) {
    if (p[i] == 1) {
      primes.push_back(i);
    }
  }
}
void solve() {
  long long int n, m;
  cin >> n >> m;
  vector<vector<long long int>> arr(n, vector<long long int>(m));
  long long int cnt = INT_MAX;
  primeSeive();
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> arr[i][j];
    }
  }
  for (int i = 0; i < n; i++) {
    long long int temp = 0;
    for (int j = 0; j < m; j++) {
      temp += primes[lower_bound(primes.begin(), primes.end(), arr[i][j]) -
                     primes.begin()] -
              arr[i][j];
    }
    cnt = min(cnt, temp);
  }
  for (int i = 0; i < m; i++) {
    long long int temp = 0;
    for (int j = 0; j < n; j++) {
      temp += primes[lower_bound(primes.begin(), primes.end(), arr[j][i]) -
                     primes.begin()] -
              arr[j][i];
    }
    cnt = min(cnt, temp);
  }
  cout << cnt << "\n";
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  cout << fixed << setprecision(12);
  int t = 1;
  for (int i = 0; i < t; i++) {
    solve();
  }
  return 0;
}
