#include <bits/stdc++.h>
using namespace std;
long long a[100000], d, n, m, r, ans = 0;
int main() {
  cin >> n >> m >> d;
  n *= m;
  cin >> a[0];
  r = a[0] % d;
  for (int i = 1; i <= n - 1; i++) {
    cin >> a[i];
    if (a[i] % d != r) {
      cout << -1;
      return 0;
    }
  }
  sort(a, a + n);
  r = a[n / 2];
  for (int i = 0; i <= n - 1; i++) {
    ans += abs(a[i] - r) / d;
  }
  cout << ans;
  return 0;
}
