#include <bits/stdc++.h>
using namespace std;
int main() {
  long int n, m, mi = 999999999, i, j, tmp = 0, res = 0, d, mid;
  cin >> n >> m >> d;
  n = n * m;
  long int A[n];
  for (i = 0; i < n; ++i) cin >> A[i];
  sort(A, A + n);
  if (A[0] == A[n - 1]) {
    cout << 0;
    return 0;
  }
  for (i = n - 1; i >= 0; --i) {
    A[i] -= A[0];
    if (A[i] % d != 0) {
      cout << -1;
      return 0;
    }
    A[i] /= d;
    mid += A[i];
  }
  for (i = 1; i < n; ++i) {
    tmp = 0;
    for (j = 0; j < n; ++j) {
      tmp += abs(A[i] - A[j]);
    }
    mid = min(tmp, mid);
  }
  cout << mid << endl;
}
