#include <bits/stdc++.h>
using namespace std;
int main() {
  int r, c, k;
  cin >> r >> c >> k;
  int a[r * c];
  for (int i = 0; i < r * c; i++) cin >> a[i];
  int rem = a[0] % k;
  bool f = true;
  for (int i = 1; i < r * c; i++) {
    if (rem != a[i] % k) f = false;
  }
  if (!f)
    cout << "-1";
  else {
    sort(a, a + r * c);
    long long int d = 0;
    for (int i = 0; i < r * c; i++) {
      d += abs(a[i] - a[(r * c) / 2]);
    }
    d /= k;
    cout << d;
  }
  cout << "\n";
}
