#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, m, k, r;
  vector<long long> v;
  cin >> n >> m >> k;
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) {
      cin >> r;
      v.push_back(r);
    }
  sort(v.begin(), v.end());
  r = v[n * m / 2];
  long long s = 0;
  for (auto it = v.begin(); it != v.end(); it++) {
    long long x = abs(*it - r);
    if (x % k == 0)
      s += x / k;
    else {
      cout << "-1";
      exit(0);
    }
  }
  cout << s;
  return 0;
}
