#include <bits/stdc++.h>
using namespace std;
bool numbers[100010];
void initi() {
  for (int i = 0; i < 100010; i++) numbers[i] = true;
}
void seive() {
  for (int i = 2; i * i <= 100010; i++) {
    if (numbers[i] == true) {
      for (int j = i * 2; j <= 100010; j = j + i) numbers[j] = false;
    }
  }
}
int main() {
  cin.tie(NULL);
  ios::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  initi();
  seive();
  numbers[1] = numbers[0] = false;
  int a[n + 2][m + 2];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int t;
      cin >> t;
      for (int k = t; k <= 100010; k++) {
        if (numbers[k] == true) {
          a[i][j] = k - t;
          break;
        }
      }
    }
  }
  long sum = long(1e5);
  for (int i = 0; i < n; i++) {
    long count = 0;
    for (int j = 0; j < m; j++) {
      count += a[i][j];
    }
    if (count < sum) sum = count;
  }
  for (int i = 0; i < m; i++) {
    long count = 0;
    for (int j = 0; j < n; j++) {
      count += a[j][i];
    }
    if (count < sum) sum = count;
  }
  cout << sum;
  return 0;
}
