#include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, int> m;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, m, a, d, mid1, mid2;
  vector<int> v;
  bool check = true;
  cin >> n >> m >> d;
  cin >> a;
  v.push_back(a);
  int b = a;
  for (int i = 1; i < n * m; i++) {
    cin >> a;
    if (abs(a - b) % d != 0) {
      check = false;
    }
    v.push_back(a);
    b = a;
  }
  sort(v.begin(), v.end());
  if (v.size() % 2 == 0) {
    mid2 = v[(v.size() / 2) - 1];
    mid1 = mid2;
  } else {
    mid2 = v[(v.size() / 2) - 1];
    mid1 = v[(v.size() / 2)];
  }
  if (check == false) {
    cout << -1;
  } else {
    int c = 0, cc = 0;
    for (int i = 0; i < n * m; i++) {
      c += (abs(v[i] - mid1) / d);
      cc += (abs(v[i] - mid2) / d);
    }
    cout << min(c, cc);
  }
  return 0;
}
