#include <bits/stdc++.h>
using namespace std;
bool primes[100005];
int sol[100005];
void sieve() {
  memset(primes, true, sizeof primes);
  primes[0] = primes[1] = false;
  int i, j;
  for (i = 2; i * i <= 100005; i++) {
    if (primes[i]) {
      for (j = i * i; j < 100005; j += i) primes[j] = false;
    }
  }
  int a = -1;
  for (i = 100005; i >= 0; i--) {
    if (primes[i]) a = i;
    sol[i] = a;
  }
}
int main() {
  int n, m;
  sieve();
  cin >> n >> m;
  int arr[n][m];
  int i, j;
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> arr[i][j];
    }
  }
  int arr1[500] = {0}, arr2[500] = {0};
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      int tmp = sol[arr[i][j]] - arr[i][j];
      arr1[i] += tmp;
      arr2[j] += tmp;
    }
  }
  int mn = 100000000;
  for (i = 0; i < n; i++) mn = min(mn, arr1[i]);
  for (i = 0; i < m; i++) mn = min(mn, arr2[i]);
  cout << mn;
  return 0;
}
