#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, d, num = 0, cnt = 0, mod = 0, ch = 0;
  cin >> n >> m >> d;
  vector<int> mat(n * m);
  for (int i = 0; i < mat.size(); i++) {
    cin >> mat[i];
    if (i == 0) {
      num = mat[i];
      mod = mat[i] % d;
    }
    if (mat[i] == num) cnt++;
    if (mat[i] % d != mod) ch = 1;
  }
  if (cnt == n * m)
    cout << 0;
  else if (ch == 1)
    cout << -1;
  else {
    sort(mat.begin(), mat.end());
    int mn = 0;
    for (int i = 0; i < mat.size(); i++)
      mn += abs(mat[i] - mat[((mat.size() - 1) / 2)]) / d;
    cout << mn;
  }
}
