#include <bits/stdc++.h>
using namespace std;
int main(int argc, char** argv) {
  int n, m, d;
  cin >> n >> m >> d;
  vector<vector<int> > v(n, vector<int>(m));
  set<int> s;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> v[i][j];
      s.insert(v[i][j]);
    }
  int h = v[0][0] % d;
  bool ok = true;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (v[i][j] % d != h) {
        ok = false;
        break;
      }
  if (!ok) {
    cout << -1;
    return 0;
  } else {
    int res = 1e9;
    for (set<int>::iterator o = s.begin(); o != s.end(); o++) {
      int u = *o, sum = 0;
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
          sum += (abs(u - v[i][j]) / d);
        }
      }
      res = min(res, sum);
    }
    cout << res;
  }
  return 0;
}
