#include <bits/stdc++.h>
using namespace std;
void sieve();
int binser(int, int, int);
vector<int> prime;
int main() {
  sieve();
  int n, m;
  cin >> n >> m;
  int num[n][m];
  int co = 0, re = 1e9;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> num[i][j];
      int x = binser(num[i][j], 0, prime.size());
      co = co + prime[x] - num[i][j];
    }
    re = min(re, co);
    co = 0;
  }
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      int x = binser(num[j][i], 0, prime.size());
      co = co + prime[x] - num[j][i];
    }
    re = min(re, co);
    co = 0;
  }
  cout << re;
  return 0;
}
int binser(int n, int low, int high) {
  if (n < 2) return 0;
  if (high < low) return -1;
  int mid = low + (high - low) / 2;
  if (prime[mid] <= n && prime[mid + 1] > n) {
    if (prime[mid] == n)
      return mid;
    else
      return mid + 1;
  } else if (prime[mid] > n)
    return binser(n, low, mid - 1);
  return binser(n, mid + 1, high);
}
void sieve() {
  bool mark[100004];
  prime.push_back(2);
  int n = 100004;
  memset(mark, true, sizeof(mark));
  int i;
  for (i = 3; i * i < n; i += 2) {
    if (mark[i] == true) {
      prime.push_back(i);
      for (int j = i * i; j < n; j += 2 * i) mark[j] = false;
    }
  }
  for (; i < n; i += 2)
    if (mark[i] == true) prime.push_back(i);
}
