#include <bits/stdc++.h>
int main() {
  int ar[1000002] = {0}, i, j, n;
  ar[0] = 1;
  ar[1] = 1;
  for (i = 4; i < 1000002; i = i + 2) ar[i] = 1;
  for (i = 3; i <= sqrt(1000002); i = i + 2) {
    if (ar[i] == 0) {
      for (j = i * i; j < 1000002; j = j + 2 * i) {
        ar[j] = 1;
      }
    }
  }
  int a[502][502] = {0}, r, c, p, rw[502], cl[502];
  while (scanf("%d %d", &r, &c) != EOF) {
    int rm = 0, cm = 0;
    int f = 1;
    rw[r] = {0}, cl[c] = {0};
    for (i = 0; i < r; i++) {
      for (j = 0; j < c; j++) {
        scanf("%d", &a[i][j]);
      }
    }
    int cnt;
    for (i = 0; i < r; i++) {
      for (j = 0; j < c; j++) {
        cnt = 0;
        if (ar[a[i][j]] == 0) {
          continue;
        } else if (a[i][j] == 1) {
          rw[i]++;
          cl[j]++;
          continue;
        } else if (a[i][j] == 0) {
          rw[i] = rw[i] + 2;
          cl[j] = cl[j] + 2;
          continue;
        } else if (a[i][j] % 2 == 0) {
          a[i][j]++;
          cnt = 1;
        }
        p = a[i][j];
        while (1) {
          if (ar[p] == 0) {
            break;
          } else
            p = p + 2;
        }
        cnt = cnt + (p - a[i][j]);
        rw[i] = rw[i] + cnt;
        cl[j] = cl[j] + cnt;
      }
      if (rw[i] == 0) {
        f = 0;
        break;
      }
    }
    if (f == 0)
      printf("0\n", i);
    else if (f == 1) {
      rm = rw[0], cm = cl[0];
      for (i = 1; i < r; i++) {
        if (rm == 0)
          break;
        else if (rm > rw[i]) {
          rm = rw[i];
        }
      }
      for (i = 1; i < c; i++) {
        if (cm == 0)
          break;
        else if (cm > cl[i])
          cm = cl[i];
      }
      if (cm > rm) {
        printf("%d\n", rm);
      } else {
        printf("%d\n", cm);
      }
    }
  }
  return 0;
}
