#include <bits/stdc++.h>
using namespace std;
template <typename TT>
istream &operator>>(istream &in, vector<TT> &v) {
  for (auto &i : v) {
    in >> i;
  }
  return in;
}
template <typename TT>
ostream &operator<<(ostream &out, vector<TT> &a) {
  for (auto &i : a) {
    out << i << " ";
  }
  return out;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n, m, d;
  cin >> n >> m >> d;
  vector<long long> tep(m, 0);
  vector<vector<long long> > a(n, tep);
  for (long long i = 0; i < n; i++) cin >> a[i];
  set<long long> x;
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) x.insert(a[i][j] % d);
  if (x.size() > 1) {
    cout << "-1\n";
    return 0;
  }
  vector<long long> b;
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) b.push_back(a[i][j]);
  sort(b.begin(), b.end());
  long long z = b.size();
  z = z / 2;
  long long final = b[z], ans = 0;
  for (long long i = 0; i < b.size(); i++) {
    ans += (abs(final - b[i]) / d);
  }
  cout << ans << "\n";
}
