#include <bits/stdc++.h>
using namespace std;
int prime[100004];
void sieve() {
  prime[1] = 1;
  for (int i = 4; i < 100004; i += 2) prime[i] = 1;
  int root = sqrt(100004);
  for (int i = 3; i <= root; i += 2) {
    if (prime[i] == 0) {
      for (int j = i * i; j < 100004; j += i * 2) {
        prime[j] = 1;
      }
    }
  }
}
int main() {
  sieve();
  int n, m, i, j;
  while (scanf("%d%d", &n, &m) == 2) {
    int input[n][m], prime_ara[n][m], row[n + m], colomn[m];
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        scanf("%d", &input[i][j]);
        if (prime[input[i][j]] == 1) {
          int tmp = input[i][j];
          while (prime[++tmp] == 1)
            ;
          prime_ara[i][j] = tmp;
        } else {
          prime_ara[i][j] = input[i][j];
        }
      }
    }
    int x = 0, sum;
    for (i = 0; i < n; i++) {
      sum = 0;
      for (j = 0; j < m; j++) {
        sum += prime_ara[i][j] - input[i][j];
      }
      row[x++] = sum;
    }
    int y = 0;
    for (i = 0; i < m; i++) {
      sum = 0;
      for (j = 0; j < n; j++) {
        sum += prime_ara[j][i] - input[j][i];
      }
      colomn[y++] = sum;
    }
    for (i = 0; i < y; i++) {
      row[x++] = colomn[i];
    }
    sort(row, row + x);
    printf("%d\n", row[0]);
  }
  return 0;
}
