#include <bits/stdc++.h>
using namespace std;
int n, m, a[600][600], r[600], c[600], pr[111118];
int check[111118];
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> a[i][j];
    }
  }
  for (int i = 1; i <= 111111; i++) {
    check[i] = 1;
  }
  check[1] = 0;
  for (int i = 2; i <= 111111; i++) {
    for (int j = i + i; j <= 111111; j += i) {
      check[j] = 0;
    }
  }
  for (int i = 2; i <= 111111; i++) {
    if (check[i] == 1) pr[i] = i;
  }
  for (int i = 111111; i >= 0; i--) {
    if (check[i] == 0) pr[i] = pr[i + 1];
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (check[a[i][j]]) {
        a[i][j] = 0;
      } else {
        a[i][j] = abs(a[i][j] - pr[a[i][j]]);
      }
    }
  }
  int ans = 999999;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      r[i] += a[i][j];
    }
    ans = min(ans, r[i]);
  }
  for (int i = 1; i <= m; i++) {
    for (int j = 1; j <= n; j++) {
      c[i] += a[j][i];
    }
    ans = min(ans, c[i]);
  }
  cout << ans;
}
