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