#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, d, x, y, sum = 0, z = 0;
  cin >> n >> m >> d;
  vector<int> v;
  for (int i = 0; i < (n * m); i++) {
    cin >> x;
    v.push_back(x);
    if (i == 0)
      y = x % d;
    else if (y != (x % d)) {
      cout << "-1";
      return 0;
    }
  }
  sort(v.begin(), v.end());
  x = *(v.begin() + (n * m) / 2);
  y = *(v.begin() + (n * m) / 2 + 1);
  for (int i = 0; i < (n * m); i++) {
    sum += abs(x - v[i]) / d;
    z += abs(y - v[i]) / d;
  }
  cout << min(sum, z);
  return 0;
}
