#include <bits/stdc++.h>
using namespace std;
void solve();
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  while (t--) {
    solve();
    cout << "\n";
  }
  return 0;
}
void solve() {
  int n, m, d;
  cin >> n >> m >> d;
  int a[n][m];
  vector<int> v;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
      v.push_back(a[i][j]);
    }
  }
  int k = a[0][0];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (k % d != a[i][j] % d) {
        cout << "-1" << endl;
        return;
      }
    }
  }
  sort(v.begin(), v.end());
  int r = v[(v.size() / 2)];
  int count = 0;
  for (int i = 0; i < v.size(); i++) {
    count += abs(v[i] - r);
  }
  cout << count / d << endl;
}
