#include <bits/stdc++.h>
int main() {
  int i, j, n, m, sum, min, index, R, P, flag, l, k;
  int A[500][500], B[500][500];
  scanf("%i%i", &n, &m);
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      scanf("%i", &A[i][j]);
    }
  }
  min = 10000000;
  for (i = 0; i < n; i++) {
    sum = 0;
    for (j = 0; j < m; j++) {
      if (A[i][j] == 1) {
        P = 2;
      } else {
        P = A[i][j];
        flag = 0;
        while (flag == 0) {
          k = 0;
          for (l = 2; l <= sqrt(P); l++) {
            if (P % l == 0) {
              k = 1;
              break;
            }
          }
          if (k == 0) {
            flag = 1;
          } else {
            P++;
          }
        }
      }
      B[i][j] = P - A[i][j];
      if (j < m - 1) {
        if (A[i][j] == A[i][j + 1]) {
          B[i][j + 1] = B[i][j];
          j++;
        }
      }
    }
  }
  for (i = 0; i < n; i++) {
    sum = 0;
    for (j = 0; j < m; j++) {
      sum = sum + B[i][j];
      if (sum > min) {
        break;
      }
    }
    if (sum < min) {
      min = sum;
    }
  }
  for (j = 0; j < m; j++) {
    sum = 0;
    for (i = 0; i < n; i++) {
      sum = sum + B[i][j];
      if (sum > min) {
        break;
      }
    }
    if (sum < min) {
      min = sum;
    }
  }
  printf("%i", min);
  return 0;
}
