#include <bits/stdc++.h>
using namespace std;
vector<long long> adj[100005];
bool vis[100005];
long long modpower(long long a, long long b, long long c) {
  long long res = 1;
  while (b) {
    if (b & 1LL) res = (res * a) % c;
    a = (a * a) % c;
    b >>= 1;
  }
  return res;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int n, m, k;
  cin >> n >> m >> k;
  int a[n][m];
  set<int> s;
  int t = 0;
  vector<int> num;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
      num.push_back(a[i][j]);
      s.insert(a[i][j] % k);
    }
  }
  if (s.size() > 1) {
    cout << "-1" << endl;
  } else {
    sort(num.begin(), num.end());
    int sum;
    if (num.size() % 2 == 0) {
      sum = (num[num.size() / 2] + num[num.size() / 2 - 1]) / 2;
    } else {
      sum = num[num.size() / 2];
    }
    auto it = s.begin();
    if (sum % k != *it) {
      sum = sum - (sum % k) + (*it);
    }
    int ans = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        int r = abs(sum - a[i][j]);
        ans += (r / k);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
