#include <bits/stdc++.h>
using namespace std;
int m, n;
int a, x[510], y[510], d[100010];
bool z[100010];
int main() {
  z[1] = 1;
  for (int i = 2; i < 100010; i++)
    if (z[i] == 0)
      for (int j = 2; j * i < 100010; j++) z[j * i] = 1;
  for (int i = 100005; i >= 1; i--) {
    if (z[i] == 1)
      d[i] = d[i + 1] + 1;
    else
      d[i] = 0;
  }
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> a;
      x[i] += d[a];
      y[j] += d[a];
    }
  sort(x, x + n);
  sort(y, y + m);
  cout << min(x[0], y[0]);
}
