#include <bits/stdc++.h>
using namespace std;
class Soln {
 private:
  int n;

 public:
  Soln() {}
  ~Soln() {}
};
class Seive {
 public:
  bool *A;
  vector<int> v;
  Seive(int n) {
    A = new bool[n + 1];
    for (int i = 0; i <= n; i++) {
      A[i] = true;
    }
    A[0] = false;
    A[1] = false;
    int stop = (int)sqrt(n);
    for (int i = 4; i <= n; i += 2) {
      A[i] = false;
    }
    for (int i = 3; i <= stop; i++) {
      if (A[i] == true) {
        for (int j = 3 * i; j <= n; j += 2 * i) {
          A[j] = false;
        }
      }
    }
    for (int i = 0; i <= n; i++) {
      if (A[i]) {
        v.push_back(i);
      }
    }
  }
  ~Seive() {
    if (!A) {
      delete[] A;
    }
  }
};
int main(int argc, char const *argv[]) {
  int n, m, **a;
  scanf("%d", &n);
  scanf("%d", &m);
  a = new int *[n];
  for (int i = 0; i < n; i++) {
    a[i] = new int[m];
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      scanf("%d", &a[i][j]);
    }
  }
  Seive sv(2000000);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int diff = 0;
      if (!binary_search(sv.v.begin(), sv.v.end(), a[i][j])) {
        int pos = upper_bound(sv.v.begin(), sv.v.end(), a[i][j]) - sv.v.begin();
        int prime = sv.v[pos];
        diff = prime - a[i][j];
      }
      a[i][j] = diff;
    }
  }
  long long int min = INT_MAX;
  for (int i = 0; i < n; i++) {
    long long int sum = 0;
    for (int j = 0; j < m; j++) {
      sum += a[i][j];
    }
    if (sum < min) {
      min = sum;
    }
  }
  for (int j = 0; j < m; j++) {
    long long int sum = 0;
    for (int i = 0; i < n; i++) {
      sum += a[i][j];
    }
    if (sum < min) {
      min = sum;
    }
  }
  printf("%-I64d\n", min);
  ;
  for (int i = 0; i < m; i++) {
    if (!a[i]) delete[] a[i];
  }
  delete[] a;
  return 0;
}
