#include <bits/stdc++.h>
using namespace std;
int a[1000][1000];
int c[100000 + 10];
int r[1000000 + 10];
bool t[1000000 + 10];
int pr[100000 + 10];
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 2; i <= 100000 + 10; i++) {
    bool k = true;
    for (int j = 2; j * j <= i; j++) {
      if (i % j == 0) {
        k = false;
      }
    }
    if (k == true) {
      t[i] = 1;
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> a[i][j];
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      int pnt = a[i][j];
      int pnt2 = a[i][j];
      while (t[pnt2] != 1) {
        pnt2++;
        r[i]++;
        c[j]++;
      }
    }
  }
  int min = 1000 * 1000 * 1000 + 1;
  for (int i = 1; i <= n; i++) {
    if (r[i] < min) {
      min = r[i];
    }
  }
  for (int i = 1; i <= m; i++) {
    if (c[i] < min) {
      min = c[i];
    }
  }
  cout << min;
}
