#include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 29;
const double EPS = 1e-10;
template <typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) {
  return os << '(' << p.first << ',' << p.second << ')';
}
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& a) {
  os << '[';
  for (int i = 0; i < (int)(a.size()); i++) os << (i ? " " : "") << a[i];
  return os << ']';
}
int main() {
  int n, m, d;
  cin >> n >> m >> d;
  bool flg = true;
  int mt[100][100];
  for (int i = 0; i < (int)(n); i++)
    for (int j = 0; j < (int)(m); j++) cin >> mt[i][j];
  for (int i = 0; i < (int)(n); i++)
    for (int j = 0; j < (int)(m); j++) {
      if (i + j == 0) continue;
      if ((mt[i][j] - mt[0][0]) % d != 0) flg = false;
    }
  if (!flg)
    cout << -1 << endl;
  else {
    int u = 0;
    for (int i = 0; i < (int)(n); i++)
      for (int j = 0; j < (int)(m); j++) {
        mt[i][j] /= d;
        u = max(u, mt[i][j]);
      }
    int ans = INF;
    for (int k = 0; k < (int)(u + 1); k++) {
      int t = 0;
      for (int i = 0; i < (int)(n); i++)
        for (int j = 0; j < (int)(m); j++) t += abs(k - mt[i][j]);
      ans = min(ans, t);
    }
    cout << ans << endl;
  }
  return 0;
}
