#include <bits/stdc++.h>
using namespace std;
int mat[102][102];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  int n, m, k;
  cin >> n >> m >> k;
  set<int> s;
  vector<int> v;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> mat[i][j];
      v.push_back(mat[i][j]);
      s.insert(mat[i][j] % k);
    }
  }
  if (s.size() > 1) {
    cout << -1 << endl;
    return 0;
  }
  sort(begin(v), end(v));
  int pos = v.size() / 2;
  int target = v[pos];
  int ans = 0;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      ans += abs(mat[i][j] - target) / k;
    }
  }
  cout << ans << endl;
  return 0;
}
