#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, t = 100010, sum = 0, mins = 100000;
  cin >> n >> m;
  set<int> s;
  vector<vector<int> > v(n, vector<int>(m));
  vector<int> b(t + 1, 0);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> v[i][j];
    }
  }
  for (int i = 2; i <= sqrt(t); i++) {
    if (b[i] != 1) {
      for (int j = i * i; j <= t; j += i) {
        b[j] = 1;
      }
    }
  }
  for (int i = 2; i < t; i++) {
    if (b[i] == 0) {
      s.insert(i);
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      set<int>::iterator p;
      p = s.lower_bound(v[i][j]);
      v[i][j] = (*p) - v[i][j];
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      sum += v[i][j];
    }
    if (mins > sum) {
      mins = sum;
    }
    sum = 0;
  }
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      sum += v[j][i];
    }
    if (mins > sum) {
      mins = sum;
    }
    sum = 0;
  }
  cout << mins;
  return 0;
}
