#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int n, m, k, count = 0;
  cin >> n >> m >> k;
  long long int s = n * m;
  long long int a[s], b[s];
  for (long long int i = 0; i < s; i++) cin >> a[i];
  sort(a, a + s);
  for (long long int i = 0; i < s; i++) {
    b[i] = abs(a[i] - a[s / 2]);
    if (b[i] % k != 0) {
      cout << -1;
      return 0;
    } else {
      count += b[i] / k;
    }
  }
  cout << count;
}
