#include <bits/stdc++.h>
using namespace std;
int main() {
  int pr[110000];
  int prev = 0;
  pr[0] = pr[1] = 2;
  for (int i = 2; i < 110000; i++) {
    bool prr = true;
    for (int j = 2; j * j <= i; j++)
      if (i % j == 0) {
        prr = false;
        break;
      }
    if (prr) {
      for (int j = prev; j <= i; j++) pr[j] = i;
      prev = i + 1;
    }
  }
  int arr[500][500];
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) cin >> arr[i][j];
  int mi = 100000 * 500;
  int sum = 0;
  for (int i = 0; i < n; i++) {
    sum = 0;
    for (int j = 0; j < m; j++) {
      sum += pr[arr[i][j]] - arr[i][j];
    }
    if (sum < mi) mi = sum;
  }
  for (int i = 0; i < m; i++) {
    sum = 0;
    for (int j = 0; j < n; j++) {
      sum += pr[arr[j][i]] - arr[j][i];
    }
    if (sum < mi) mi = sum;
  }
  cout << mi << endl;
  return 0;
}
