#include <bits/stdc++.h>
using namespace std;
int prime[100001] = {0};
bool check_prime(int n) {
  if (n == 1) {
    return 0;
  }
  if (n == 2) {
    return 1;
  }
  if (n == 3) {
    return 1;
  }
  for (int i = 2; i <= sqrt(n); i++) {
    if (n % i == 0) {
      return 0;
    }
  }
  return 1;
}
int next_prime(int n) {
  if (n == 1 || n == 2) {
    return 2;
  }
  int x = n;
  while (check_prime(x) != 1) {
    x++;
  }
  return x;
}
int main() {
  int n, m;
  cin >> n >> m;
  int a[n][m];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  for (int i = 1; i < 100001; i++) {
    int x = next_prime(i);
    while (i <= x) {
      prime[i] = x;
      i++;
    }
    i--;
  }
  int move = 1000000000;
  for (int i = 0; i < n; i++) {
    int t = 0;
    for (int j = 0; j < m; j++) {
      t += prime[a[i][j]] - a[i][j];
    }
    if (t == 0) {
      cout << 0;
      return 0;
    }
    move = min(move, t);
  }
  for (int j = 0; j < m; j++) {
    int t = 0;
    for (int i = 0; i < n; i++) {
      t += prime[a[i][j]] - a[i][j];
    }
    if (t == 0) {
      cout << 0;
      return 0;
    }
    move = min(move, t);
  }
  cout << move;
  return 0;
}
