#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAXN = 1e5 + 3;
const int inf = 2e9;
int max(int a, int b) {
  if (a > b)
    return a;
  else
    return b;
}
int min(int a, int b) {
  if (a < b)
    return a;
  else
    return b;
}
bool cmp(pair<int, int> p1, pair<int, int> p2) {
  if (p1.first < p2.first)
    return true;
  else if (p1.first == p2.first) {
    if (p1.second < p2.second) return true;
    return false;
  }
  return false;
}
void solve() {
  int n, m, d;
  cin >> n >> m >> d;
  int a[n][m];
  for (int i = (int)0; i < (int)n; ++i) {
    for (int j = (int)0; j < (int)m; ++j) {
      cin >> a[i][j];
    }
  }
  int check = a[0][0] % d;
  vector<int> v;
  bool pr = false;
  for (int i = (int)0; i < (int)n; ++i) {
    for (int j = (int)0; j < (int)m; ++j) {
      if (a[i][j] % d == check) {
        v.push_back(a[i][j]);
      } else {
        pr = true;
        break;
      }
    }
  }
  if (pr)
    cout << -1 << "\n";
  else {
    sort((v).begin(), (v).end());
    int cc = (n * m);
    int bi = (cc / 2);
    int ans = 0;
    for (int i = (int)0; i < (int)cc; ++i) {
      ans += abs(v[i] - v[bi]);
    }
    cout << ans / d << "\n";
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
