#include <bits/stdc++.h>
using namespace std;
int n, m;
int arr[509][502], s[100000];
int l = 1;
int dem[1005], ans;
int main() {
  s[0] = 2;
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> arr[i][j];
    }
  }
  for (int i = 3; i <= 100003; i++) {
    int k = 0;
    for (int j = 2; j * j <= i; j++)
      if (i % j == 0) {
        k++;
        break;
      }
    if (k == 0) {
      s[l] = i;
      l++;
    }
  }
  int x = 0;
  for (int i = 0; i < n; i++) {
    int z = 0;
    for (int j = 0; j < m; j++) {
      int cac = lower_bound(s, s + l, arr[i][j]) - s;
      z += (s[cac] - arr[i][j]);
    }
    dem[x] = z;
    x++;
  }
  for (int j = 0; j < m; j++) {
    int z = 0;
    for (int i = 0; i < n; i++) {
      int cac = lower_bound(s, s + l, arr[i][j]) - s;
      z += (s[cac] - arr[i][j]);
    }
    dem[x] = z;
    x++;
  }
  sort(dem, dem + x);
  cout << dem[0];
  return 0;
}
