#include <bits/stdc++.h>
int cad[150000];
int n, m;
int matrix[501][501];
int revolution[501][501];
int i, j;
void criba(int n) {
  cad[1] = 1;
  for (i = 2; i <= n; i++) {
    if (cad[i] >= 0) {
      for (j = i + i; j < n; j += i) {
        cad[j] = 1;
      }
    }
  }
}
int main() {
  int i, j, ars, l, vector, menor = 100000;
  scanf("%d%d", &n, &m);
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      scanf("%d", &matrix[i][j]);
    }
  }
  criba(150000);
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      ars = 0;
      l = matrix[i][j];
      while (cad[l] != 0) {
        l++;
        ars++;
        cad[l];
      }
      revolution[i][j] = ars;
    }
  }
  for (i = 0; i < n; i++) {
    vector = 0;
    for (j = 0; j < m; j++) {
      vector += revolution[i][j];
    }
    if (vector < menor) {
      menor = vector;
    }
  }
  for (j = 0; j < m; j++) {
    vector = 0;
    for (i = 0; i < n; i++) {
      vector += revolution[i][j];
    }
    if (vector < menor) {
      menor = vector;
    }
  }
  printf("%d", menor);
  return 0;
}
