#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 10005;
int a[MAX_N];
int p[MAX_N];
int main() {
  memset(p, 0, sizeof(p));
  int n, m, k;
  cin >> n >> m >> k;
  int v = 0;
  for (int i = 0; i < n * m; i++) {
    cin >> a[i];
    if (abs(a[i] - a[0]) % k != 0) v = 1;
    p[a[i]]++;
  }
  if (v) {
    cout << "-1" << endl;
    return 0;
  }
  int l = 1, r = 10000;
  while (p[l] == 0) l++;
  while (p[r] == 0) r--;
  long long int ans = 0;
  while (l != r) {
    if (p[l] < p[r]) {
      p[l + k] += p[l];
      ans += p[l];
      p[l] = 0;
      l++;
    } else {
      p[r - k] += p[r];
      ans += p[r];
      p[r] = 0;
      r--;
    }
  }
  cout << ans << endl;
  return 0;
}
