#include <bits/stdc++.h>
using namespace std;
long long int sieve[1000000], large[1000000];
int main() {
  long long int n, m, max = 0, i, j, cou = 0;
  cin >> n;
  cin >> m;
  vector<vector<long long int> > v(n, vector<long long int>(m));
  for (i = 0; i < n; i = i + 1) {
    for (j = 0; j < m; j = j + 1) {
      cin >> v[i][j];
      if (max > v[i][j]) max = v[i][j];
    }
  }
  for (i = 1; i < 1000000; i = i + 1) sieve[i] = 0;
  i = 2;
  large[1] = 1;
  long long int last = 1, found = 0;
  while (i < 1000000 && found == 0) {
    if (sieve[i] == 0) {
      for (j = i * i; j < 1000000; j = j + i) sieve[j] = i;
      for (j = last; j <= i; j = j + 1) {
        large[j] = i;
        if (j == max) found = 1;
      }
      last = i + 1;
    }
    i++;
  }
  long long int mi = -1;
  for (i = 0; i < n; i = i + 1) {
    cou = 0;
    for (j = 0; j < m; j = j + 1) {
      cou = cou + large[v[i][j]] - v[i][j];
    }
    if (mi == -1)
      mi = cou;
    else if (cou < mi)
      mi = cou;
  }
  for (i = 0; i < m; i = i + 1) {
    cou = 0;
    for (j = 0; j < n; j = j + 1) {
      cou = cou + large[v[j][i]] - v[j][i];
    }
    if (cou < mi) mi = cou;
  }
  cout << mi << "\n";
  return 0;
}
