#include <bits/stdc++.h>
using namespace std;
int pc, notPrime[3130], P[10000], A[502][502], B[502][502];
void sieve(int n) {
  int i, j;
  (notPrime[1 >> 5] |= (1 << (1 & 31)));
  for (j = 2 * 2; j <= n; j += 2) (notPrime[j >> 5] |= (1 << (j & 31)));
  for (i = 3; i * i <= n; i += 2)
    if ((!(notPrime[i >> 5] & (1 << (i & 31)))))
      for (j = i * i; j <= n; j += (i << 1))
        (notPrime[j >> 5] |= (1 << (j & 31)));
  P[pc++] = 2;
  for (i = 3; i <= n; i += 2)
    if ((!(notPrime[i >> 5] & (1 << (i & 31))))) P[pc++] = i;
}
long long solve(int n, int m) {
  int maxA = 0, i, j;
  long long sum, minSum = 1000000000000000000ll;
  for (i = 0; i < n; ++i)
    for (j = 0; j < m; ++j)
      if (maxA < A[i][j]) maxA = A[i][j];
  sieve(maxA + 75);
  for (i = 0; i < n; ++i)
    for (j = 0; j < m; ++j)
      B[i][j] = *lower_bound(P, P + pc, A[i][j]) - A[i][j];
  for (i = 0; i < n; ++i) {
    sum = 0;
    for (j = 0; j < m; ++j) sum += B[i][j];
    if (minSum > sum) minSum = sum;
  }
  for (j = 0; j < m; ++j) {
    sum = 0;
    for (i = 0; i < n; ++i) sum += B[i][j];
    if (minSum > sum) minSum = sum;
  }
  return minSum;
}
int main() {
  int n, m, i, j;
  scanf("%d %d", &n, &m);
  for (i = 0; i < n; ++i)
    for (j = 0; j < m; ++j) scanf("%d", &A[i][j]);
  printf("%I64d\n", solve(n, m));
  return 0;
}
